python - 匹配元组中的字符串 - python

标签 python list tuples concatenation

我必须(字符串,计数器)形式的元组列表,例如

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/

相关文章:

python - Django 2.0 访问模型(CREATE/REMOVE/FILTER)独立 [没有 manage.py shell]

python - pandas 对不规则间隔时间数据进行重新采样

python - 作为列表列表的字典元素的总和

python - 如何在一个语句中从列表中删除多个项目?

python - 如何在 Python 中正确合并重叠的日期时间范围

ios - 如何快速获取键值对元组数组?

python - 极地 python : split string in lazyframe column into new columns

python - 如何同时绘制不同产品的时间序列图?

python - 我可以使用 groupby 在 Pandas 数据框中创建每行都是运行列表的列吗?

java - 在Java中应用MapReduce