简体   繁体   English

将列表列表转换为元组列表

[英]Converting a list of lists to a list of tuples

I have got a list of lists: 我有一个清单清单:

[['AB', '132'], ['C D'], ['EFG'], ['HJ K', '2  1']]  

and i am trying to convert it into a list of tuples: 我正在尝试将其转换为元组列表:

[('AB', '132'), ('C D', ''), ('EFG', ''), ('HJ K', '2  1')]

Exceedingly simple, just use a list comprehension to loop over the source list and convert each element to a tuple, by directly passing the items to the tuple builtin : 极其简单,只需使用列表推导就可以将源项目直接传递给内置的元组,从而遍历源列表并将每个元素转换为元tuple

>>> example = [['AB', '132'], ['C D'], ['EFG'], ['HJ K', '2 1']]
>>> [tuple(i) for i in example]
[('AB', '132'), ('C D',), ('EFG',), ('HJ K', '2 1')]

Alternatively, if you like functional programming, use map instead: 另外,如果您喜欢函数式编程,请改用map

>>> map(tuple, example)
[('AB', '132'), ('C D',), ('EFG',), ('HJ K', '2 1')]

list comprehension will convert each element of your list into a tuple: 列表推导会将列表中的每个元素转换为元组:

data = [['AB', '132'], ['C D'], ['EFG'], ['HJ K', '2 1']]
[tuple(elem) for elem in data]

gives: 给出:

[('AB', '132'), ('C D',), ('EFG',), ('HJ K', '2 1')]

One possibility is to use map(tuple, l) : 一种可能性是使用map(tuple, l)

In [1]: l=[['AB', '132'], ['C D'], ['EFG'], ['HJ K', '2  1']]  

In [2]: map(tuple, l)
Out[2]: [('AB', '132'), ('C D',), ('EFG',), ('HJ K', '2  1')]

The downside is that in Python 3, this would return an iterable instead of a list. 缺点是在Python 3中,这将返回一个可迭代的列表,而不是列表。 If you have to have a list, this will need to be spelled out as list(map(tuple, l)) (this works in both Python 2 and 3). 如果必须要有一个列表,则需要将其拼写为list(map(tuple, l)) (这在Python 2和3中都适用)。

Another approach that works in both Python 2 and 3 is to use a list comprehension: 在Python 2和3中都可以使用的另一种方法是使用列表理解:

[tuple(x) for x in l]

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

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