简体   繁体   English

将元组附加到列表

[英]append tuples to a list

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]
result.extend(item)

You can use the inbuilt list() function to convert a tuple to a list. 您可以使用内置的list()函数将元组转换为列表。 So an easier version is: 所以一个简单的版本是:

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]]

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])

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. 您将需要对数值进行一些处理,以使其正确显示,但这将是另一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM