2014-01-19 104 views
1

我不得不形式(字符串,计数器)的元组的列表,像匹配字符串元组 - 蟒蛇

tuples1 = [('A', 4), ('D', 8), ('L', 38)] 
tuples2 = [('A', 24), ('B', 84), ('C', 321), ('D', 19) ...] 

所以第一清单第二列表中有字符串的一个子集,但有一个不同的数字 - 字符串的数量 - 列表中的每个字符串。所以我想要列表1中的所有字符串,其中都是数字。

我想使它成为一个形式('字符串',tuples1 [1],tuples2 [1])三个项的列表。所以对于例如字符串'D',它将是('D',8,19)。我想我需要为tuples1中的每个字符串做一些事情,将一个项目追加到列表中(tuples1 [i] [0],tuples1 [i] [1],tuples2 [matchStringIndex] [ 1])。
如何编程?

+0

你应该真的使用'collections.Counter'来做你的计数,或者至少使用基于dict的数据结构而不是元组列表。 – roippi

+0

我使用'collections.Counter', '计数= collections.Counter(利斯特) sortedCounter = counted.most_common() tuplesIT =排序(sortedCounter)#tuples形式( '单词', '实例')的推文中的所有单词 - “推文中的元组” – AndrewSB

回答

1

您可以将元组,其中有一个列表中进行搜索,字典,然后从那个字典上的相应计数,这样

tuples1 = [('A', 4), ('D', 8), ('L', 38)] 
tuples2 = [('A', 24), ('B', 84), ('C', 321), ('D', 19), ("L", 15)] 
dict_tuples2 = dict(tuples2) 
print [(char, count, dict_tuples2.get(char, 0)) for char, count in tuples1] 

输出

[('A', 4, 24), ('D', 8, 19), ('L', 38, 15)]