Python 弹出负数有效,但不适用于零

Python 弹出负数有效,但不适用于零,python,list,dictionary,for-loop,Python,List,Dictionary,For Loop,在我的代码中,我使用字典:{2:f',0:x',4: “z',-3:“z'}作为参数,并将其转换为列表。我应该打印出一定数量的字母(值),由其键(整数)给出,例如,键对4:“z”表示字母z将打印4次。我指定任何小于1的键都不应该被输出,它对键-3有效,但是出于某种原因,键0仍然出现,尽管我已经指定弹出任何小于1的整数键。这就是我目前的输出: 1. 0. <--- This should be removed 2: ff 4: zzzz 守则: def draw_rows(dictiona

在我的代码中,我使用字典:{2:f',0:x',4: “z',-3:“z'}作为参数,并将其转换为列表。我应该打印出一定数量的字母(值),由其键(整数)给出,例如,键对4:“z”表示字母z将打印4次。我指定任何小于1的键都不应该被输出,它对键-3有效,但是出于某种原因,键0仍然出现,尽管我已经指定弹出任何小于1的整数键。这就是我目前的输出:

1.
0. <--- This should be removed
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'})
def draw_行(字典):
turn\u list=list(dictionary.keys())
turn_list.sort()
对于轮次列表中的num:
如果num<1:
turn\u list.pop(turn\u list[num])
对于轮换钥匙列表:
打印(键“:”,字典[键]*键,sep=”“)
def test_draw_rows():
打印(“1”)
绘制行({2:f',0:x',4:z',-3:z'})

首先,从列表中弹出元素
turn\u list
,它是字典列表的副本
turn\u 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()
这两种情况下的输出都是

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()
def draw_行(字典):
#遍历字典
对于键,dictionary.items()中的值:
#仅打印满足条件的k-v对
如果不是键<1:
打印(键“:”,值*键,sep=”“)
def test_draw_rows():
打印(“1”)
绘制行({2:f',0:x',4:z',-3:z'})
测试\绘制\行()

如果您喜欢更简单的代码,那么下面的代码应该可以使用

def draw_rows(dictionary):
    for k, v in dictionary.items():
        if k > 0:
            print(k, ':', v * k)

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):
    for k, v in dictionary.items():
        if k > 0:
            print(k, ':', v * k)

def test_draw_rows():
    print('1.')
    draw_rows({2: 'f', 0: 'x', 4: 'z', -3: 'z'})

test_draw_rows()
1.
2 : ff
4 : zzzz