如何将元组列表连接到python元组中的连接项目列表中?
问题描述:
我有一个元组列表,我想制作一个简单的字符串列表,这些列表由元组中的每个元素串联组成。即:如何将元组列表连接到python元组中的连接项目列表中?
a = [("as","b","c"),("d","e"),("f","g")]
B.将= ["as b c","d e","f g"]
我想这一个:
b = [sum(i,[]) for i in a ]
,但我得到
TypeError: can only concatenate tuple (not "str" to tuple)`
答
,用空格加入多个字符串,你应该使用str.join()
。这需要一点时间来适应,因为你把它叫做你想使用它来加入其他字符串的字符串,在这种情况下,空格字符:
>>> map(" ".join, a)
['as b c', 'd e', 'f g']
有些人喜欢列表理解了这一点:
[" ".join(t) for t in a]
我对python的知识感到失望,同时努力寻找解决方案,有时它只是如此“小菜一碟” – curious 2012-02-28 13:47:27
@curious:我建议花时间阅读[基本数据类型的文档] (http://docs.python.org/library/stdtypes.html)。它会得到回报。 – 2012-02-28 13:51:06