2024-05-18 07:34:53 发布
网友
假设我有一个字符串"abcdefghijklmnopqrstuvwxyz",我想用这些值初始化字典键。
"abcdefghijklmnopqrstuvwxyz"
alphabet = 'abcdefghijklmnopqrstuvwxyz' alphabetDict = dict() for char in alphabet: alphabetDict[char] = 0
有更好的办法吗?
您可以在Python中使用字典理解。
alphabetDict = {char: 0 for char in alphabet}
Dictionaries(Python文档)
这个答案和上面的答案有一点不同。Dict理解评估每个键的值,而fromkeys只做一次。如果你用的是ints之类的东西,这没问题。但是,如果你这样做了
fromkeys
d = {key: [] for key in <some set>} d[3].append(5) print(d[2])
给你
[]
你有不同的清单
d = dict.fromkeys(<some set>, []) d[3].append(5) print(d[2])
[5]
将所有键映射到同一列表。
是的,您可以在一行中使用dictionary comprehensions.
In [1]: alphabet = 'abcdefghijklmnopqrstuvwxyz' In [2]: {x:0 for x in alphabet} # dictionary comprehension Out[2]: {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0}
您可以使用^{}方法-
>>> s = 'abcdefghijklmnopqrstuvwxyz' >>> alphaDict = dict.fromkeys(s,0) >>> alphaDict {'m': 0, 'p': 0, 'i': 0, 'n': 0, 'd': 0, 'w': 0, 'k': 0, 'y': 0, 's': 0, 'b': 0, 'h': 0, 't': 0, 'u': 0, 'q': 0, 'g': 0, 'l': 0, 'e': 0, 'a': 0, 'j': 0, 'c': 0, 'o': 0, 'f': 0, 'v': 0, 'x': 0, 'z': 0, 'r': 0}
来自documentation -
fromkeys(seq[, value])Create a new dictionary with keys from seq and values set to value.fromkeys() is a class method that returns a new dictionary. value defaults to None.
fromkeys(seq[, value])
Create a new dictionary with keys from seq and values set to value.
fromkeys() is a class method that returns a new dictionary. value defaults to None.
fromkeys()
None
请注意,如果value是list或其他dict等可变的,则不应使用此选项,因为当调用方法fromkeys()时,该值仅被求值一次,并且所有键都指向同一对象。
value
list
dict
对于不可变类型,可以将其用作int、str等值
int
str
另外,您不需要指定s或alphabet字符串,而是可以使用^{}。示例-
s
alphabet
>>> import string >>> alphaDict = dict.fromkeys(string.ascii_lowercase,0) >>> alphaDict {'m': 0, 'p': 0, 'i': 0, 'n': 0, 'd': 0, 'w': 0, 'k': 0, 'y': 0, 's': 0, 'b': 0, 'h': 0, 't': 0, 'u': 0, 'q': 0, 'g': 0, 'l': 0, 'e': 0, 'a': 0, 'j': 0, 'c': 0, 'o': 0, 'f': 0, 'v': 0, 'x': 0, 'z': 0, 'r': 0}
您可以在Python中使用字典理解。
Dictionaries(Python文档)
这个答案和上面的答案有一点不同。Dict理解评估每个键的值,而
fromkeys
只做一次。如果你用的是ints之类的东西,这没问题。但是,如果你这样做了给你
你有不同的清单
给你
将所有键映射到同一列表。
是的,您可以在一行中使用dictionary comprehensions.
您可以使用^{} 方法-
来自documentation -
请注意,如果
value
是list
或其他dict
等可变的,则不应使用此选项,因为当调用方法fromkeys()
时,该值仅被求值一次,并且所有键都指向同一对象。对于不可变类型,可以将其用作
int
、str
等值另外,您不需要指定} 。示例-
s
或alphabet
字符串,而是可以使用^{相关问题 更多 >
编程相关推荐