【问题标题】:In python how can I match two lists of tuples by a tuple element?在 python 中,如何通过元组元素匹配两个元组列表?
【发布时间】:2011-04-14 00:33:23
【问题描述】:

假设我有 names 作为包含任意顺序名称元组的元组列表:

names = [(1,"Alice"), (2,"Bob")]

genders 作为另一个包含任意顺序的性别元组的元组列表:

genders = [(2,"male"), (1,"female")]

如何通过使用元组的第一个元素作为获取键来有效地匹配两个列表:

result = [("Alice","female"), ("Bob","male")]

【问题讨论】:

    标签: python list tuples


    【解决方案1】:

    简单的单行答案,运行缓慢:

    [(name, gender) for (id0, gender) in genders for (id1, name) in names if id0==id1]
    

    更好的答案(参见 Ignazio 的回复):

    namedict = dict(names)
    genderdict = dict(genders)
    [(namedict[id], genderdict[id]) for id in set(namedict) & set(genderdict)]
    

    【讨论】:

    • 那是O(n^2),而首先创建字典并迭代是O(3n) ~ O(n)...只是说,您不想为长列表这样做。
    【解决方案2】:

    转换为字典、收集键并进行迭代。

    【讨论】:

      猜你喜欢
      • 2015-05-03
      • 1970-01-01
      • 2018-04-15
      • 2017-03-22
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      相关资源
      最近更新 更多