弹出一个负数有效但不能为零

时间:2019-05-25 06:37:36

标签: python list dictionary for-loop pop

在我的代码中,我使用了一个字典:{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'})

2 个答案:

答案 0 :(得分:1)

首先,您要从列表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()

如果目标只是打印,我们可以遍历键,仅打印必要的键和值对。

plt.savefig(dir)

答案 1 :(得分:1)

如果您希望使用更简单的代码,则下面的代码应该可以使用。

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