我必须(字符串,计数器)形式的元组列表,例如
tuples1 = [('A', 4), ('D', 8), ('L', 38)]
tuples2 = [('A', 24), ('B', 84), ('C', 321), ('D', 19) ...]
因此,第一个列表是第二个列表所具有的字符串的子集,但对于列表中的每个字符串具有不同的数字(字符串的计数)。所以我想要列表 1 中的所有字符串,以及两个数字。
我想将其变成一个由三个术语组成的列表,其形式为 ('string', tuples1[1], tuples2[1])。例如,对于字符串 'D',它将是 ('D', 8, 19)。
我想象我需要对 tuples1 中的每个字符串执行类似的操作,将一个项目附加到包含 (tuples1[i][0], tuples1[i][1], tuples2[matchStringIndex][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)]
关于python - 匹配元组中的字符串 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21222103/