简体   繁体   English

if-else对字典的理解在python3中不起作用

[英]if-else comprehension with dictionary not working in python3

dlist=['All my loving','All my bros','And all sis']

I would like to create a dictionary such that all words (as keys) are assigned a value which is index of dlist in which the words appear. 我想创建一个字典,以便为所有单词(作为键)分配一个值,该值是出现单词的dlist的索引。 For example, 'All':{0,1}, 'my':{0,1},'sis'={2} etc. 例如,“全部”:{0,1},“我的”:{0,1},“ sis” = {2}等。

Somehow this does not work: 以某种方式这不起作用:

dict={}
{w:{num} if w not in dict.keys() else dict[w].add(num) for (num,strn) in enumerate(dlist) for w in strn.split()}

This returns 这返回

{'All':{2}, 'my':{2}}

Looks like else statement is being ignored. 看起来else语句被忽略了。 Any pointers? 有指针吗? Thanks 谢谢

This doesn't work because you are trying to access dict.keys while you are creating dict in a dict comprehension. 这不起作用,因为在dict理解中创建dict时,您尝试访问dict.keys。 If this was in a for loop, dict.keys would be updated each element, but the dict comprehensions ensures that the dict is not updated mid-creation to improve speed. 如果这是在for循环中,则将为每个元素更新dict.keys,但是dict理解可确保dict不会在中间创建时进行更新以提高速度。

Something like this should work: 这样的事情应该起作用:

myDict = {}
for (num, strn) in enumerate(dlist):
    for w in strn.split():
        if w not in myDict:
            myDict[w] = {num}
        else:
            myDict[w].add(num)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM