gpt4 book ai didi

python - 修改字典中的所有值

转载 作者:太空狗 更新时间:2023-10-30 00:28:40 25 4
gpt4 key购买 nike

代码如下:

d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad' #a string
indices = map(s.index, d.keys()) #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices)) #this is how I do it, any better way?
print d #{'a':2, 'c':0, 'b':1, 'd':3}

还有其他方法吗?

附言。上面的代码只是一个简单的代码来演示我的问题。

最佳答案

这样的事情可能会使您的代码更具可读性:

dict([(x,y) for y,x in enumerate('cbad')])

但是你应该详细说明你真正想做什么。如果 s 中的字符不适合 d 的键,您的代码可能会失败。所以 d 只是键的容器,值并不重要。在这种情况下,为什么不从列表开始呢?

关于python - 修改字典中的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7104436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com