Python 将元组附加到列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3274095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
append tuples to a list
提问by DGT
How can I append the content of each of the following tuples (ie, elements within the list) to another list which already has 'something' in it? So, I want to append the following to a list (eg: result[]) which isn't empty:
如何将以下每个元组(即列表中的元素)的内容附加到另一个已经包含“某物”的列表中?所以,我想将以下内容附加到一个非空的列表(例如:result[])中:
l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)]
Obviously, the following doesn't do the thing:
显然,以下不会做的事情:
for item in l:
result.append(item)
print result
I want to printout:
我想打印:
[something, 'AAAA', 1.11]
[something, 'BBB', 2.22]
[something, 'CCCC', 3.33]
采纳答案by Ignacio Vazquez-Abrams
result.extend(item)
回答by cletus
You can use the inbuilt list()function to convert a tuple to a list. So an easier version is:
您可以使用内置list()函数将元组转换为列表。所以一个更简单的版本是:
l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)]
result = [list(t) for t in l]
print result
Output:
输出:
[['AAAA', 1.1100000000000001],
['BBB', 2.2200000000000002],
['CCCC', 3.3300000000000001]]
回答by Kit
You will need to unpack the tuple to append its individual elements. Like this:
您需要解包元组以附加其各个元素。像这样:
l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)]
for each_tuple in l:
result = ['something']
for each_item in each_tuple:
result.append(each_item)
print result
You will get this:
你会得到这个:
['something', 'AAAA', 1.1100000000000001]
['something', 'BBB', 2.2200000000000002]
['something', 'CCCC', 3.3300000000000001]
You will need to do some processing on the numerical values so that they display correctly, but that would be another question.
您需要对数值进行一些处理,以便它们正确显示,但这将是另一个问题。
回答by John
You can convert a tuple to a list easily:
您可以轻松地将元组转换为列表:
>>> t = ('AAA', 1.11)
>>> list(t)
['AAAA', 1.11]
And then you can concatenate lists with extend:
然后你可以连接列表extend:
>>> t = ('AAA', 1.11)
>>> result = ['something']
>>> result.extend(list(t))
['something', 'AAA', 1.11])

