【问题标题】:How to do unpack this nested tuple in better way?如何以更好的方式解包这个嵌套元组?
【发布时间】:2018-09-04 11:13:00
【问题描述】:

我有一个叫做记录的元组

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

这是预期结果

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])

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

问候

【问题讨论】:

  • 这些总是2元组吗?如果是这样,你真的不需要嵌套循环。另外,如果records 有超过 2 个元组会发生什么?
  • 是的,..它们是 2 元组 @DeepSpace

标签: python python-3.x list tuples


【解决方案1】:

对于元组列表:

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

expected_result = list(zip(*records))
expected_result 

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

对于列表的元组:

expected_result = tuple(map(list,zip(*records)))
expected_result

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

对于元组的元组:

expected_result = tuple(zip(*records))
expected_result

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

【讨论】:

  • 只是一个小小的吹毛求疵:OP 想要一个列表元组。这将返回一个元组列表。
  • 结果在列表中,而不是元组中。 ?
【解决方案2】:

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

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

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

与您想要的输出不同,1 将保持为整数。

【讨论】:

  • 似乎也很复杂,pythonic .. :)
  • 好消息是这些内置插件都经过了高度优化。没有 Python 级别的 for 循环。
【解决方案3】:

更pythonic的方法是使用函数zip创建一个迭代器。

例如:

result = list(zip(*records))

将返回一个包含两个元组的列表:

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

通过使用 listtuple 构造函数,您可以获得预期的结果(两个列表的一个元组):

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多