python - 弹出负数可以,但不能用于零

标签 python list dictionary for-loop

在我的代码中,我使用字典:{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/

相关文章:

java - 如何将 "Pair"或 n 大小插入列表集合而不是组成 HashMap?

c# - 使用用户定义的转换将字符串转换为类型安全的枚举

python - 根据日期范围对 Panda Dataframe 中的数据进行排序和过滤

Python:如何将值添加到字典中的现有值

java - 对于我不明白的事情,在这里得到一个空指针异常

c# - 如何将列表复制到数组

python - 哪些索引数组值位于特定误差范围内?

python - 在 Python 中获取最后一个 '/' 或 '\\' 字符

list - 使用一个递归函数和 FoldBack 函数实现插入排序

dictionary - 我如何在 Flutter 中实现 map (不是 Google map )?