更改变量字典中基础变量的值



如何使用字典更改变量的值?现在我必须检查字典中的每个键,然后更改相应变量的值。

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
dictionary = {
"dog": list1,
"cat": list2,
"mouse": list3
}
animal = input("Type dog, cat or mouse: ")
numbers_list = dictionary[animal]
# Adds 1 to all elements of the list
numbers_list = [x+1 for x in numbers_list]
# Is there an easier way to do this?
# Is there a way to change the value of the original list without
# using large amount of if-statements, since we know that
# dictionary[animal] is the list that we want to change?
# Using dictionary[animal] = numbers_list.copy(), obviously wont help because it
# only changes the list in the dictionary
if animal == "dog":
list1 = numbers_list.copy()
if animal == "cat":
list2 = numbers_list.copy()
if animal == "mouse":
list3 = numbers_list.copy()
print(list1, list2, list3)

我试过使用dictionary[animal] = numbers_list.copy()但这只是改变了字典中的值,而不是实际的列表。这些if语句是有效的,但是如果有一个大的字典,那就需要大量的工作。

您可以动态地用新列表替换dict值-

dictionary[animal] = [i+1 for i in dictionary[animal]]

我建议停止使用listx变量,并使用dict本身来维护这些列表和映射。

dictionary = {
"dog": [1, 2, 3],
"cat": [4, 5, 6],
"mouse": [7, 8, 9]
}
animal = "cat"
dictionary[animal] = [i+1 for i in dictionary[animal]]
print(dictionary[animal])
#instead of printing list1, list2, list3, print the key, values in the dict
for animal, listx in dictionary.items():
print(animal, listx)

输出:

[5, 6, 7]
dog [1, 2, 3]
cat [5, 6, 7]
mouse [7, 8, 9]

无需单独的列表。你可以直接赋值列表作为字典定义的一部分。

animals = {
"dog": [1, 2, 3],
"cat": [4, 5, 6],
"mouse": [7, 8, 9]
}
animal = input("Type dog, cat or mouse: ")

一旦你知道了动物的名字,你就可以直接遍历列表并增加每个数字:

for i in range(len(animals[animal])):
animals[animal][i] += 1

最新更新