Python:将元组列表转换为平面列表

时间:2013-11-09 18:47:15

标签: python

您如何编码以下结果?

tuple_list = [('a', 1), ('b', 3), ('c', 2), ...]
def flatten_tuple(tuple_list):
    magic_happens here
    return flat_list
flat_list = ['a', 1, 'b', 3, 'c', 2, ...]

解决这个问题是一个简单的问题:

def flatten_tuple(tuple_list):
    flat_list = []
    for a, b in tuple_list:
        flat_list.append(a)
        flat_list.append(b)
    return flat_list

我是否遗漏了一些可以在不重复列表本身的情况下压扁元组列表的内容?

2 个答案:

答案 0 :(得分:2)

使用itertools.chain

from itertools import chain

tuple_list = [('a', 1), ('b', 3), ('c', 2)]

list(chain.from_iterable(tuple_list))
Out[5]: ['a', 1, 'b', 3, 'c', 2]

或嵌套列表理解:

[elem for sub in tuple_list for elem in sub]
Out[6]: ['a', 1, 'b', 3, 'c', 2]

答案 1 :(得分:1)

你可以使用像这样的列表理解来展平它

tuple_list = [('a', 1), ('b', 3), ('c', 2)]
def flatten_tuple(tuple_list):
    #Method 1
    #import itertools
    #return [item for item in itertools.chain.from_iterable(tuple_list)]

    #Method 2
    return [item for tempList in tuple_list for item in tempList]

print flatten_tuple(tuple_list)

或者通过这个优秀的答案https://stackoverflow.com/a/952952/1903116注意仅适用于Python 2)

tuple_list = [('a', 1), ('b', 3), ('c', 2)]
def flatten_tuple(tuple_list):
    return list(reduce(lambda x,y: x + y, tuple_list))

print flatten_tuple(tuple_list)