简体   繁体   English

将元组与多个项目python合并

[英]Merge tuple with multiple item python

I need my script to merge tuples with multiple items.我需要我的脚本来将元组与多个项目合并。 I have:我有:

list = [('France', 'Euro', 'Paris'), ('France', 'Euro', 'Marseille'), 
('Allemagne', 'Euro', 'Berlin'),
('Allemagne', 'Euro', 'Hambourg'), ('Allemagne', 'Euro', 'Munich'),
('France', 'Euro', 'Lyon'), ('Turquie', 'Livre', 'Ankara')]

and I want:而且我要:

list = [('France', 'Euro', 'Paris', 'Marseille', 'Lyon'), 
('Allemagne', 'Euro', 'Berlin', 'Hambourg', 'Munich'),
('Turquie', 'Livre', 'Ankara')]

I have found :我已经找到 :

for t in j:
    d.setdefault(t[0], set()).add(t[1])
result = tuple(tuple([k]+list(v)) for k, v in d.items())

But I can only merge item if I have 2 item per line.但是如果每行有 2 个项目,我只能合并项目。

I have tried to modify the logic but have not succeeded.我试图修改逻辑但没有成功。

There are multiple problems with your code:您的代码存在多个问题:

  1. You are looking to group by Country and Currency.您正在寻找按国家和货币分组。 Yet your dictionary only uses Country keys.然而你的字典只使用 Country 键。
  2. Your tuple comprehension will only ever return a tuple, while you want a list of tuples as output.你的元组理解只会返回一个元组,而你想要一个元组列表作为输出。
  3. You are shadowing the built-in list class, you should never do this.您正在隐藏内置list类,您永远不应该这样做。

You can instead use collections.defaultdict with tuple keys, followed by a list comprehension:您可以改为使用带有元组键的collections.defaultdict ,然后是列表理解:

from collections import defaultdict

d = defaultdict(list)

for ctry, ccy, city in L:
    d[(ctry, ccy)].append(city)

res = [k+tuple(v) for k, v in d.items()]

print(res)

[('France', 'Euro', 'Paris', 'Marseille', 'Lyon'),
 ('Allemagne', 'Euro', 'Berlin', 'Hambourg', 'Munich'),
 ('Turquie', 'Livre', 'Ankara')]

It seems to me that you want to iterate through the list, and combine the third element (being the currency) of each tuple which contains the same second and first element在我看来,您想遍历列表,并组合包含相同第二个第一个元素的每个元组的第三个元素(即货币)

This is how I would proceed:这就是我将继续的方式:

currencies = {}
for i in lists:
    if (i[0],i[1]) in currencies.keys():
        currencies[(i[0],i[1])] = currencies[(i[0],i[1])]|set([i[2]])
    else:
        currencies[(i[0],i[1])] = set([i[2]])
lists = []
for c in currencies:
    lists.append(list(c) + list(currencies[c]))
print(lists)

this will yield: [['France', 'Euro', 'Marseille', 'Lyon', 'Paris'], ['Allemagne', 'Euro', 'Berlin', 'Munich', 'Hambourg'], ['Turquie', 'Livre', 'Ankara']] Though the result is not a tuple in the list, it still sorts the data, hope this helps!这将产生: [['France', 'Euro', 'Marseille', 'Lyon', 'Paris'], ['Allemagne', 'Euro', 'Berlin', 'Munich', 'Hambourg'], ['Turquie', 'Livre', 'Ankara']]虽然结果不是列表中的元组,但它仍然对数据进行排序,希望这会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM