【问题标题】:Is there a proper function to merge two lists and flatten at the same time?是否有适当的功能来合并两个列表并同时展平?
【发布时间】:2021-12-08 17:46:11
【问题描述】:

我有一个说名字的列表,然后是一个列表列表,每个名字都有不同的属性(名字的位置相当于属性列表的位置)。我想将这些列表组合成具有以下结构的元组列表:[(name, attribute), ...]

示例代码:

names = ['alice', 'bob']
attributes = [['tall', 'blue eyes'], ['small']]

finished_list = SomeMagicFunction(names, attributes)

finished_list
[('alice', 'tall'), ('alice', 'blue eyes'), ('bob', 'small')]

我知道下面提到的列表理解有效(与 zip() 结合使用),但我想知道是否有适当的函数可以做到这一点。

test = list(zip(names, attributes))
[(tuple[0], attribute) for tuple in test for attribute in tuple[1]]
[('alice', 'tall'), ('alice', 'blue eyes'), ('bob', 'small')]

【问题讨论】:

  • 您所说的“正确功能”是指您提到的list(zip()) 方法的手工实现吗?或者更确切地说是一个包含代码的单一干净函数调用?
  • @ethanmorton 感谢您的澄清问题。 “适当的功能”是指类似于zip()itertools.product() 等的一些标准功能,因为在我看来这似乎是一个相当标准的问题。
  • 在某种意义上,使用list(zip()) 是您正在寻找的更通用的功能。正如您所提到的,我认为生成器方面基本上就是您要问的。大多数 Python 开发人员(至少我见过)会看到 list(zip()) 并认为它已经是一个非常干净的实现,本质上就像一个函数调用,所以没有人实现它的抽象。
  • @ethanmorton 好吧,我想我觉得这很奇怪。非常感谢您的反馈!

标签: python python-3.x list


【解决方案1】:

没有标准功能,但列表理解非常好,尽管它可能更惯用:

  1. 不需要中间列表test
  2. 解压,以便您可以使用描述性名称,例如for name, attrs in zip...
>>> [(name, attr) for name, attrs in zip(names, attributes) for attr in attrs]
[('alice', 'tall'), ('alice', 'blue eyes'), ('bob', 'small')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-25
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2014-01-04
    • 2018-03-18
    相关资源
    最近更新 更多