简体   繁体   English

python:从元组列表中删除列表括号

[英]python : Removing list brackets from list of tuples

I apologise if there are dupes.如果有骗子,我很抱歉。 I've only found codes that remove tuples from list, but not the list itself.我只找到了从列表中删除元组的代码,而不是列表本身。 I have a constant我有一个常数

a = [[(1,2,3),(3,2,1)], [(2,1,6),(7,3,2),(1,0,2)]]

And I'd like to remove all the brackets inside a so it becomes我想删除 a 内a所有括号,这样它就变成了

a = (1,2,3),(3,2,1),(2,1,6),(7,3,2),(1,0,2)

Is it possible to do it in a simple way?是否有可能以简单的方式做到这一点? I've tried something similar to我试过类似的东西

for i in a:
    print(a[0], a[1], a[2])

but the number of tuples in each interior list vary, so I can't just use [0] etc..但是每个内部列表中的元组数量各不相同,所以我不能只使用 [0] 等。

IIUC, try chain.from_iterable IIUC,试试chain.from_iterable

from itertools import chain

print([i for i in chain.from_iterable(a)])

[(1, 2, 3), (3, 2, 1), (2, 1, 6), (7, 3, 2), (1, 0, 2)]

One possible way to this is by using reduce .一种可能的方法是使用reduce

>>> from functools import reduce
>>> reduce(lambda a,b : tuple(a+b),a)
((1, 2, 3), (3, 2, 1), (2, 1, 6), (7, 3, 2), (1, 0, 2))
a = [[(1,2,3),(3,2,1)], [(2,1,6),(7,3,2),(1,0,2)]]

for _list in a:
    for _tuple in _list:
        print(_tuple)

Use list comprehension, however, you will get of list of tuples, for what you've mentioned in the desired output, you need to unpack the tuples with the same number of variables:使用列表理解,但是,您将获得元组列表,对于您在所需的 output 中提到的内容,您需要使用相同数量的变量解包元组:

a = [x for l in a for x in l]

Output: Output:

[(1, 2, 3), (3, 2, 1), (2, 1, 6), (7, 3, 2), (1, 0, 2)]

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

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