回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我知道这篇文章底部的代码的逻辑/语法是错误的,但是我很难弄清楚如何写这个来得到想要的结果。第一节创建此词典:</p>
<pre><code>sco = {'human + big': 0, 'big + loud': 0, 'big + human': 0, 'human + loud': 0, 'loud + big': 0, 'loud + human': 0}
</code></pre>
<p>然后,我的意图是对字典“cnt”中的每个项循环一次x,然后对字典循环第二次x,每次该项的值与(cnt[x][1])相同,但键不同(cnt[x][0]),创建一个字符串,该字符串将匹配字典“sco”中的格式“%s+%s”。然后,它将在sco中找到与分配给变量dnt的键匹配的键,并将sco中该键的值递增1。你知道吗</p>
<pre><code># -*- coding: utf-8 -*-
import itertools
sho = ('human', 'loud', 'big')
sco = {}
for a,b in itertools.permutations(sho, 2):
sco["{0} + {1}".format(a,b)] = 0
cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')]
for x in cnt:
upd = cnt[x][0]
who = cnt[x][1]
for x in cnt:
if cnt[x][0] != upd and cnt[x][1] == who:
cpg = cnt[x][0]
dnt = '%s + %s' % (upd, cpg)
for i in sco:
if sco[i][0] == dnt:
sco[i][1] += sco[i][1]
print sco
</code></pre>
<p>目前,打印sco不会导致任何值的更改。代码的预期结果如下:</p>
<pre><code>{'human + big': 1, 'big + loud': 0, 'big + human': 1, 'human + loud': 2, 'loud + big': 0, 'loud + human': 2}
</code></pre>
<p>非常感谢您的帮助!你知道吗</p>
<p>修订后的代码如下:</p>
<pre><code># -*- coding: utf-8 -*-
import itertools
sho = ('human', 'loud', 'big')
sco = {}
for a,b in itertools.permutations(sho, 2):
sco["{0} + {1}".format(a,b)] = 0
cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')]
for x in cnt:
upd = cnt[0]
who = cnt[1]
for x in cnt:
if cnt[0] != upd and cnt[1] == who:
cpg = cnt[0]
dnt = '%s + %s' % (upd, cpg)
sco[dnt] += 1
print sco
</code></pre>
<p>下面的代码实现了我的意图。感谢@dermen&;abarnert:</p>
<pre><code># -*- coding: utf-8 -*-
import itertools
sho = ('human', 'loud', 'big')
sco = {}
for a,b in itertools.permutations(sho, 2):
sco["{0} + {1}".format(a,b)] = 0
cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')]
for x in cnt:
upd = x[0]
who = x[1]
for x in cnt:
if x[0] != upd and x[1] == who:
cpg = x[0]
dnt = '%s + %s' % (upd, cpg)
sco[dnt] += 1
print sco
</code></pre>