我有以下词典:

items = {1: ['1a', '3c', '2a', '1b', '2a', '1b', '1a', '2b', '1a', '2b'], 2: ['1a', '3c', '2a', '1b', '2a', '1b', '1a', '2b', '1a', '2b']}

我想为每个列表添加所有“相似”值的整数分量。
(Similar means that the strings end with the same character.)
我希望最终结果是:
items = {1: ['7a', '3c', '6b'], 2: ['7a', '3c', '6b']}

最佳答案

这将起作用:

from collections import defaultdict

items = {1: ['1a', '3c', '2a', '1b', '2a', '1b', '1a', '2b', '1a', '2b'],
         2: ['1a', '3c', '2a', '1b', '2a', '1b', '1a', '2b', '1a', '2b']}

for key, value in items.items():
    counting = defaultdict(int)
    for elem in value:
        counting[elem[1]] += int(elem[0])
    items[key] = [str(v) + k for k,v in counting.items()]

print(items)

关于python - 在字典列表python中添加相同的字母数字值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47460288/

10-13 04:12