【问题标题】:how to find the same element in list of tuple and substitute it in Python?如何在元组列表中找到相同的元素并在 Python 中替换它?
【发布时间】:2015-08-03 21:42:44
【问题描述】:

我有一个这样的元组列表:

 t= [('A', 3000, '20140304'), ('B', 2000, '20140304'),('DD',3000, '20140304'), ('N', 102, '20140305'), ('S', 136, '20140305'), ('N', 182, '20140305'),('G',136, '20140305')]

我想知道它是否在同一日期有相同的价格。如果是,则返回一个带有名称的元组对的新列表。输出应如下所示:

[('A','DD'),('S','G')]

【问题讨论】:

  • 那么就开始写一些代码吧。
  • 我尝试使用索引和循环但不起作用

标签: python python-3.x tuples


【解决方案1】:

您可以将元组聚合成一个defaultdict,其中一个元组(price, date) 作为键。遍历该默认字典,并返回包含多个项目的任何名称列表。

from collections import defaultdict

price_date_dict = defaultdict(list)

for name, price, date in t:
    price_date_dict[(price, date)].append(name)

return [tuple(names) for names in price_date_dict.values() if len(names) > 1]

【讨论】:

  • 我认为需要price_date_dict.items()
  • @JuniorCompressor 是的,这是不正确的。谢谢。
【解决方案2】:
import collections as coll

t = [('A', 3000, '20140304'), ('B', 2000, '20140304'),('DD',3000, '20140304'), ('N', 102, '20140305'), ('S', 136, '20140305'), ('N', 182, '20140305'),('G',136, '20140305')]

d = coll.defaultdict(lambda:coll.defaultdict(set))
for a,p,stackOverflow in t: d[stackOverflow][p].add(a)

for t in d:
    for p in d[t]:
        print("On day", t, ", the following items were sold at price", p, ':\n' + ','.join(sorted(d[t][p])))

【讨论】:

    猜你喜欢
    • 2015-09-06
    • 2018-08-16
    • 2018-04-17
    • 1970-01-01
    • 2018-01-11
    • 2019-02-20
    • 2017-02-20
    • 2018-08-18
    • 2023-04-02
    相关资源
    最近更新 更多