随机选择列表
random selection of list
我有这个列表,每次都会随机选择一个不同的值,如何打印单独选择的随机值的键?
import random
a_dictionary = {"winter": 10, "summer": 30,"spring":20,"autumn":15}
values = list(a_dictionary.values())
key = list(a_dictionary.keys())
randomx= random.choice( values)
print(randomx)
#print(randomx.key)
示例:随机值=
20
spring
也许你可以试试:
key, value = random.choice(list(a_dictionary.items()))
或者,如果您无法控制进行选择的过程(即您只有值),您可以使用反向字典:
rev_dict = {v: k for k, v in a_dictionary.items()}
# and later, say your randomx is 20
>>> rev_dict[randomx]
'spring'
尝试使用 .items()
import random
a_dictionary = {"winter": 10, "summer": 30,"spring":20,"autumn":15}
print(random.choice(list(a_dictionary.items()))) # prints ('winter', 10)
这应该有效。
import random
dict = {
"winter" : 10,
"summer" : 30,
"spring": 20,
"autumn" : 15
}
values = list(dict.values())
keys = list(dict.keys())
random = random.choice(values)
print(random)
print(keys[values.index(random)])
您不必遍历 VALUES 列表,而是遍历 ITEMS 列表:
season, number = random.choice(list(a_dictionary.items()))
我有这个列表,每次都会随机选择一个不同的值,如何打印单独选择的随机值的键?
import random
a_dictionary = {"winter": 10, "summer": 30,"spring":20,"autumn":15}
values = list(a_dictionary.values())
key = list(a_dictionary.keys())
randomx= random.choice( values)
print(randomx)
#print(randomx.key)
示例:随机值=
20
spring
也许你可以试试:
key, value = random.choice(list(a_dictionary.items()))
或者,如果您无法控制进行选择的过程(即您只有值),您可以使用反向字典:
rev_dict = {v: k for k, v in a_dictionary.items()}
# and later, say your randomx is 20
>>> rev_dict[randomx]
'spring'
尝试使用 .items()
import random
a_dictionary = {"winter": 10, "summer": 30,"spring":20,"autumn":15}
print(random.choice(list(a_dictionary.items()))) # prints ('winter', 10)
这应该有效。
import random
dict = {
"winter" : 10,
"summer" : 30,
"spring": 20,
"autumn" : 15
}
values = list(dict.values())
keys = list(dict.keys())
random = random.choice(values)
print(random)
print(keys[values.index(random)])
您不必遍历 VALUES 列表,而是遍历 ITEMS 列表:
season, number = random.choice(list(a_dictionary.items()))