python - 弹出一个负数有效但不为零
问题描述
在我的代码中,我将字典:{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'})
解决方案
首先,您从 list 中弹出元素turn_list
,它是 list of dictionaries 的副本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()
推荐阅读
- javascript - reactjs中的登录页面验证
- python - 如何比较列表和列表中的列表
- amazon-web-services - AWS CLI (Windows) 中缺少检测自定义标签
- swift - 可选项返回 nil 的精确点
- angular - Mat Checkbox 当'Y'时不改变
- mysql - 如何将 SQL 查询转换为 Eloquent Laravel
- sonarqube - jenkins 管道中的 Sonarqube 阶段因 403 错误而失败
- data-structures - 如何组合数据点的两个属性(每个属性具有相反的影响)以过滤出最佳数据点?
- python - 合并和覆盖两个 DataFrame 中的公共列
- amazon-web-services - 执行 aws-lambda 时出现参数列表太长错误