我想加载列表,然后在列表中找到其索引号相似的项目。然后,我将创建一个字典来存储这些索引号。 索引号应存储在同一词典中。
我的代码:
a = ["a" , "b" , "c" , "d" , "r" , "g" , "h" , "f" , "a", "b" ,"c" , "c" , "c" , "f", "f" , "a" , "a" , "h" ]
aa = []
index = []
for x in a:
aa.append(x)
dd = {}
if x in aa:
dd[x] = [a.index(x)]
index.append(dd)
print(index)
当前输出:
[{'a': [0]}, {'b': [1]}, {'c': [2]}, {'d': [3]}, {'r': [4]}, {'g': [5]}, {'h': [6]}, {'f': [7]}, {'a': [0]}, {'b': [1]}, {'c': [2]}, {'c': [2]}, {'c': [2]}, {'f': [7]}, {'f': [7]}, {'a': [0]}, {'a': [0]}, {'h': [6]}]
例如:
预期输出:
[{'a': [0, 8, 15, 16]}, {'b': [1, 9]}, {'c': [2,10,11,12]}, {'d': [3]}, {'r': [4]}, {'g': [5]}, {'h': [6,17]}, {'f': [7,13,14]}]
或者如果可能的话,预期的输出也可以是这样的:
[[0, 8, 15, 16],[1, 9],[2,10,11,12],[3],[4],[5],[6,17],[7,13,14]]
我尝试了许多其他方法,但是它保持不同的保存方式,而不是在字典中为多个值保存相同的键
答案 0 :(得分:1)
使用collection.defaultdict
例如:
from collections import defaultdict
a = ["a" , "b" , "c" , "d" , "r" , "g" , "h" , "f" , "a", "b" ,"c" , "c" , "c" , "f", "f" , "a" , "a" , "h" ]
d = defaultdict(list)
for i, v in enumerate(a): #enumerate to get index
d[v].append(i)
print(d)
print(d.values())
输出:
defaultdict(<type 'list'>, {'a': [0, 8, 15, 16], 'c': [2, 10, 11, 12], 'b': [1, 9], 'd': [3], 'g': [5], 'f': [7, 13, 14], 'h': [6, 17], 'r': [4]})
[[0, 8, 15, 16], [2, 10, 11, 12], [1, 9], [3], [5], [7, 13, 14], [6, 17], [4]]