如何以更好的方式解压缩此嵌套元组?

时间:2018-09-04 11:13:01

标签: python python-3.x list tuples

我有一个称为记录的元组

records =(['foo', 1]),(['bar', 'hello'])

这是Expected_result

expected_result= (['foo','bar'],['1','hello'])

我为此创建了一个For循环,并且效果很好

for i in range(len(records[0])):
    for k in range(len(records[1])):
        if i==k:
            j,v = records
            print(j[i],v[i])

有没有更好的方法来使用最少的代码和行?

致谢

3 个答案:

答案 0 :(得分:5)

对于元组列表:

CONVERT

对于列表元组:

SUBSTRING

对于元组的元组:

records =(['foo', 1]),(['bar', 'hello'])

expected_result = list(zip(*records))
expected_result 

[('foo', 'bar'), (1, 'hello')]

答案 1 :(得分:2)

这是一种返回列表元组的方法:

records = (['foo', 1]), (['bar', 'hello'])
res = tuple(map(list, zip(*records)))

# (['foo', 'bar'], [1, 'hello'])

与所需的输出不同,1将保留为整数。

答案 2 :(得分:2)

更Python化的方式是使用功能 zip 进行迭代。

例如:

result = list(zip(*records))

将返回两个元组的列表:

[('foo', 'bar'), (1, 'hello')]

同时使用 list tuple 构造函数,可以得到预期的结果(两个列表中的一个元组):

expected_result = tuple(list(item) for item in zip(*records))
print(expected_result)

(['foo', 'bar'], [1, 'hello'])