我有一个单词列表(function mysql_compatible_crc32($s) {
$r = crc32($s);
if($r<0) {
return 4294967296+$r;
}
return $r;
}
)和一个以前原始的字典(listwords = ['a', 'b', 'c']
),其目的是创建一个新的字典,其中键将是列表词,其元素将是数量一。额外的标识以及原始词典中出现了多少个单词。代码如下:
dictwords = {'111': '['a', 'a', 'b']', '112': '['b', 'a', 'b']'}
最终结果应为以下内容:
for i in listwords:
addlist= []
for k, x in dictwords.items():
if i in x:
cont = 0
cont = x.count(i)
addlist.append(k)
addlist.append(cont)
newdict[i] = addlist
即它应该是新字典中具有各自计数列表的键,但是结果是这样的:
a -> ['111', 2], ['112', 1]
b -> ['111', 2], ['112', 1]
c -> ['111', 0], ['112', 0]
有人知道我要去哪里吗?我应该插入一个新列表,然后插入新字典吗?
答案 0 :(得分:2)
您不必遍历子数组,您的.count
会为您完成。相反,请遍历listwords
中的键,这样就不必多次检查同一字符。
尝试以下方法:
for i in listwords:
addlist= []
for k, x in dictwords.items():
addlist.append({k: x.count(i)})
newdict[i] = addlist
>>> newdict
{'a': [{'111': 2}, {'112': 1}], 'b': [{'111': 1}, {'112': 2}], 'c': [{'111': 0}, {'112': 0}]}
您还可以使用简单的列表/字典理解来实现目标:
>>> {i: [{key: dictwords[key].count(i)} for key in dictwords] for i in listwords}
{'a': [{'111': 2}, {'112': 1}], 'b': [{'111': 1}, {'112': 2}], 'c': [{'111': 0}, {'112': 0}]}
答案 1 :(得分:1)
有人知道我要去哪里吗?我应该插入一个新列表,然后插入新字典吗?
您本身不需要插入新列表,只需更改初始化addlist
的位置。假设您想要一个列表列表,则需要为addlist
中的每个键初始化dictwords
。这意味着将addlist = []
移动到for k, x in dictwords.items():
下。
现在,您无需让addlist
为newdict
中的每个字母创建一个列表,而是将newdict
分配给listwords
中的键,并且 append < / em> addlist
到每个字母的列表。有两种不同的方法可以执行此操作,但是一个非常优雅的解决方案是使用defaultdict
模块中的collections
。使用defaultdict
并移动addlist
的定义,您应该看起来像这样:
from collections import defaultdict
listwords = ['a', 'b', 'c']
dictwords = {'111': "['a', 'a', 'b']", '112': "['b', 'a', 'b']"}
newdict = defaultdict(list)
for i in listwords:
for k, x in dictwords.items():
addlist= []
if i in x:
cont = 0
cont = x.count(i)
addlist.append(k)
addlist.append(cont)
newdict[i].append(addlist)
打印newdict
应该给你这样的东西:
defaultdict(<class 'list'>, {'a': [['111', 2], ['112', 1]], 'b': [['111', 1], ['112', 2]]})
您当然可以根据自己的目的使输出更漂亮。
答案 2 :(得分:0)
你是对的。现在,所有条目都指向同一列表,并且您正在对其进行变异。
occurences = {}
for word in list_of_words:
list_to_store = []
for key, words in dict_of_words.items():
list_to_store.append((key, words.count(word)))
occurences[word] = list_to_store
您还可以使用列表理解:
occurences = {}
for word in list_of_words:
occurences[word] = [(key, words.count(word))
for key, words in dict_of_words.items()]
您还可以将其与dict理解相结合:
occurences = {
word: [(key, words.count(word))
for key, words in dict_of_words.items()]
for word in list_of_words
}
这看起来更加简洁。
输出代码:
for k, v in occurences.items():
print(f"{k} -> {v}")
输出:
a -> [('111', 2), ('112', 1)]
b -> [('111', 1), ('112', 2)]
c -> [('111', 0), ('112', 0)]