[英]grouping elements into new list from two lists using python
I have two really long lists in python, the first with words in english, and the second with spanish words. 我在python中有两个很长的列表,第一个带有英语单词,第二个带有西班牙语单词。 Because the second list is generated from the first list, a lot of elements are repeated, so I need a way to group those elements with the respective translation.
因为第二个列表是从第一个列表生成的,所以重复了很多元素,因此我需要一种将这些元素与各自的翻译进行分组的方法。
for example: 例如:
#my two lists
a=['car', 'house', 'wagon', 'rat', 'mouse', 'cart']
b=['carro', 'casa', 'carro', 'raton', 'raton', 'carro']
#the resulting list must be something like this
c=['car, wagon, cart: carro', 'house: casa', 'rat, mouse: raton']
thanks in advance 提前致谢
ps it's not a homework, it's a small program that I'm trying to create to learn vocabulary ps这不是家庭作业,而是我正在尝试创建的一个用于学习词汇的小程序
If order doesn't matter I would just go with this: 如果顺序无关紧要,我就可以这样做:
>>> from collections import defaultdict
>>> a=['car', 'house', 'wagon', 'rat', 'mouse', 'cart']
>>> b=['carro', 'casa', 'carro', 'raton', 'raton', 'carro']
>>> d = defaultdict(list)
>>> for k, v in zip(b, a):
d[k].append(v)
This is what d
looks like: 这是
d
样子:
>>> d
defaultdict(<type 'list'>, {'casa': ['house'], 'carro': ['car', 'wagon', 'cart'], 'raton': ['rat', 'mouse']})
And to get the final result 并获得最终结果
>>> ['{0}: {1}'.format(', '.join(v), k) for k, v in d.items()]
['house: casa', 'car, wagon, cart: carro', 'rat, mouse: raton']
If order does matter, and you need that result exactly: 如果顺序很重要,而您确实需要该结果:
>>> d = OrderedDict()
>>> for k, v in zip(b, a):
d.setdefault(k, []).append(v)
>>> ['{0}: {1}'.format(', '.join(v), k) for k, v in d.items()]
['car, wagon, cart: carro', 'house: casa', 'rat, mouse: raton']
>>> dic = {}
>>> for v, k in zip(a, b):
dic.setdefault(k, []).append(v)
>>> ["{}: {}".format(', '.join(v),k) for k,v in dic.iteritems()]
['house: casa', 'car, wagon, cart: carro', 'rat, mouse: raton']
Something like this: 像这样:
#!/bin/env python
import pprint
a=['car', 'house', 'wagon', 'rat', 'mouse', 'cart']
b=['carro', 'casa', 'carro', 'raton', 'raton', 'carro']
d = {}
for pair in zip(a,b):
if pair[1] not in d: d[pair[1]] = []
d[pair[1]].append(pair[0])
pprint.pprint(d)
Prints: 打印:
{'carro': ['car', 'wagon', 'cart'],
'casa': ['house'],
'raton': ['rat', 'mouse']}
You could format it differently, just loop through the dictionary d
. 您可以采用不同的格式,只需遍历字典
d
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.