-2

I have a list of tuple like this:

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

I want to find if it has a same price on same date. If it does, return a new list of tuple pair with the name.The output should like this:

[('A','DD'),('S','G')]
Toffee H
  • 21
  • 3

2 Answers2

0
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])))
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
0

You can aggregate the tuples into a defaultdict with a tuple of (price, date) as the key. Iterate through that defaultdict, and return any list of names with more than one item.

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]
Community
  • 1
  • 1
horns
  • 1,843
  • 1
  • 19
  • 26