在我的代码中,我使用字典:{2: 'f', 0: 'x', 4: 'z', -3: 'z'} 作为参数并将其转为列表。我应该打印出一定数量的字母(值),由其键(整数)给出,例如,键对 4: 'z' 意味着字母 z 将被打印 4 次。我指定根本不应该输出任何小于 1 的键,并且它适用于键 -3,但由于某种原因,尽管我已指定弹出任何小于 1 的整数键,但键 0 仍然出现。这就是什么我的输出现在看起来像:
1.
0. <--- This should be removed
2: ff
4: zzzz
但它应该是这样的:
1.
2: ff
4: zzzz
代码:
def draw_rows(dictionary):
turn_list = list(dictionary.keys())
turn_list.sort()
for num in turn_list:
if num < 1:
turn_list.pop(turn_list[num])
for key in turn_list:
print(key,": ", dictionary[key] * key, sep="")
def test_draw_rows():
print("1.")
draw_rows({2: 'f', 0: 'x', 4: 'z', -3: 'z'})
最佳答案
首先,您从列表 turn_list
中弹出元素,该列表是字典列表 turn_list = list(dictionary.keys())
的副本,
从该列表中弹出元素不会影响原始字典。
因此,您希望通过迭代字典的副本来弹出原始字典本身中的键,因为在迭代字典时无法更新字典
def draw_rows(dictionary):
#Take copy of the dictionary
dict_copy = dictionary.copy()
#Iterate over the copy
for key in dict_copy:
#If key is less than 1, pop that key-value pair from dict
if key < 1:
dictionary.pop(key)
#Print the dictionary
for key in dictionary:
print(key,": ", dictionary[key] * key, sep="")
def test_draw_rows():
print("1.")
draw_rows({2: 'f', 0: 'x', 4: 'z', -3: 'z'})
test_draw_rows()
您还可以通过字典理解来简化代码,即使用 key > 1
创建一个新字典
def draw_rows(dictionary):
#Use dictionary comprehenstion to make a dictionary with keys > 1
dictionary = {key:value for key, value in dictionary.items() if key > 0}
#Print the dictionary
for key in dictionary:
print(key,": ", dictionary[key] * key, sep="")
def test_draw_rows():
print("1.")
draw_rows({2: 'f', 0: 'x', 4: 'z', -3: 'z'})
test_draw_rows()
这两种情况的输出都是
1.
2: ff
4: zzzz
如果目标只是打印,我们可以迭代键,并仅打印必要的键和值对。
def draw_rows(dictionary):
#Iterate over dictionary
for key, value in dictionary.items():
#Print only those k-v pairs which satisfy condition
if not key < 1:
print(key,": ", value * key, sep="")
def test_draw_rows():
print("1.")
draw_rows({2: 'f', 0: 'x', 4: 'z', -3: 'z'})
test_draw_rows()
关于python - 弹出负数可以,但不能用于零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56302392/