-1

您将如何为以下结果编码?

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

我是否遗漏了一些可以展平元组列表而不迭代列表本身的东西?

4

2 回答 2

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]
于 2013-11-09T18:52:01.660 回答
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)
于 2013-11-09T18:52:48.670 回答