擅长:python、mysql、java
<p>请尝试以下操作:</p>
<pre><code>>>> lst = ['a', 'A', 'b', 'B', 'c', 'C']
>>> dct = dict(zip(lst[::2],lst[1::2]))
>>> dct
{'a': 'A', 'b': 'B', 'c': 'C'}
</code></pre>
<p>解释:</p>
<pre><code>>>> lst[::2]
['a', 'b', 'c']
>>> lst[1::2]
['A', 'B', 'C']
>>> zip(lst[::2], lst[1::2])
# this actually gives a zip iterator which contains:
# [('a', 'A'), ('b', 'B'), ('c', 'C')]
>>> dict(zip(lst[::2], lst[1::2]))
# here each tuple is interpreted as key value pair, so finally you get:
{'a': 'A', 'b': 'B', 'c': 'C'}
</code></pre>
<p><strong>注意</strong>:不要将变量命名为python关键字。你知道吗</p>
<p>正确的程序版本是:</p>
<pre><code>lst = ['a', 'A', 'b', 'B', 'c', 'C']
dct = {}
for n in range(0,int(len(lst)/2)):
dct.update({lst[n]: lst[n+1]})
print(dct)
</code></pre>
<p>你的不起作用,因为你在每次迭代中都使用了切片,而不是访问每个元素。<code>lst[0::2]</code>给出<code>['a', 'b', 'c']</code>,<code>lst[1::2]</code>给出<code>['A', 'B', 'C']</code>。因此,在第一次迭代中,当<code>n == 0</code>您试图用对<code>['a', 'b', 'c'] : ['A', 'B', 'C']</code>更新字典时,您将得到一个类型错误,因为<code>list</code>不能被指定为字典的键,因为<code>list</code>是不可损坏的。你知道吗</p>