我知道下面的语法是off的,但是我很难理解应该如何编写这个语法。我想要做的是把列表“列表”创建一个字典,其中键是每个单词与另一个单词的组合,这个词本身不是,每个键的值是0。这是我的破译代码:
lst = ('human', 'loud', 'big')
for words in lst:
first = words
for words in lst:
if words != first:
scores = {'%s + %s': 0, % (first, words)}字典应该是这样的:
scores = {'human + loud': 0, 'human + big': 0, 'loud + big': 0, 'loud + human': 0, 'big + loud': 0, 'big + human': 0}任何帮助都是非常感谢的!
编辑:将列表类型更改为lst。
发布于 2015-05-05 05:18:53
我有一个更紧凑的功能。
import itertools
scores = {}
for a,b in itertools.permutations(('human', 'loud', 'big'), 2):
scores["{0} + {1}".format(a,b)] = 0
print scores发布于 2015-05-05 03:57:17
字典赋值行有语法问题,但更重要的问题是每次都要重新分配字典。
相反,在开始时创建字典,然后添加到字典中。
最后,list不是一个好的变量名,因为它与类型的名称发生冲突。
mylist = ('human', 'loud', 'big')
scores = {}
for w in mylist:
for v in mylist:
if w != v:
scores['%s + %s' % (w, v)] = 0
print scores发布于 2015-05-05 03:59:35
尝试以下几点:
lst = ('human', 'loud', 'big')
scores = {}
for f in lst:
for s in lst:
if f != s:
scores['{0} + {1}'.format(f, s)] = 0
print scores因此:
>>> lst = ('human', 'loud', 'big')
>>> scores = {}
>>> for f in lst:
... for s in lst:
... if f != s:
... scores['{0} + {1}'.format(f, s)] = 0
...
>>> print scores
{'human + big': 0, 'big + loud': 0, 'big + human': 0, 'human + loud': 0, 'loud + big': 0, 'loud + human': 0}
>>> https://stackoverflow.com/questions/30043982
复制相似问题