Python:如何用lis中的stepindex更新字典

2024-05-15 00:05:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个星期大的Python学习者。我想知道:比如说:

list= [“a”, “A”, “b”, “B”, “c”, “C”]

我需要在字典中更新它们以得到如下结果:

dict={“a”:”A”, “b”:”B”, “c”:”C”}

我尝试在dict.update({list[n::2]: list[n+1::2]}for n in range(0,(len(list)/2))中使用列表索引

我想我做错了什么。请纠正我。你知道吗

先谢谢你。你知道吗


Tags: in列表forlen字典updaterange学习者
3条回答

请尝试以下操作:

>>> lst = ['a', 'A', 'b', 'B', 'c', 'C']
>>> dct = dict(zip(lst[::2],lst[1::2]))
>>> dct
{'a': 'A', 'b': 'B', 'c': 'C'}

解释:

>>> 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'}

注意:不要将变量命名为python关键字。你知道吗

正确的程序版本是:

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)

你的不起作用,因为你在每次迭代中都使用了切片,而不是访问每个元素。lst[0::2]给出['a', 'b', 'c']lst[1::2]给出['A', 'B', 'C']。因此,在第一次迭代中,当n == 0您试图用对['a', 'b', 'c'] : ['A', 'B', 'C']更新字典时,您将得到一个类型错误,因为list不能被指定为字典的键,因为list是不可损坏的。你知道吗

下面的代码非常适合你的问题。希望这对你有帮助

a = ["a", "A", "B","b", "c","C","d", "D"]
b = {}
for each in range(len(a)):
    if each % 2 == 0:
        b[a[each]] = a[each + 1]
print(b)

你可以这样使用字典理解:

>>> l = list("aAbBcCdD")
>>> l
['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
>>> { l[i] : l[i+1] for i in range(0,len(l),2)}
{'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}

相关问题 更多 >

    热门问题