从字典中过滤偶数和奇数值并将这些偶数和奇数值添加到列表并将它们写入 txt 文件

filter even and odd values from a dictionary and add these even and odd values to lists and write them to a txt file

代码:

def even_odd_split(Dic1):
    even = []
    odd =  []
    for sublist in Dic1.values():
        for x in sublist:
            if x % 2 == 0:
            even.append(x)
            else:
            odd.append(x)
    return even, odd
 Dic1  = {"N1": [1, 3, 7, 6, 10],
      "N2": [2, 3, 9, 10, 21, 36],
      "N3": [4, 6, 5, 12, 24, 35],
      "N4": [0, 3, 14, 15, 16, 18]
     }

     print('Even items: %s\nOdd items%s' % even_odd_split(Dic1))

     with open("odd.txt","w") as f:
             f.write(str(odd))

     with open("even.txt","w") as f:
             f.write(str(even))

错误:名称 'odd' 未定义

是不是没有找到,因为它在列表中是空的,但我添加了偶数和奇数。我不明白你为什么要这样 error.How 我可以修复错误吗?

变量有范围。如果它们在一个方法中,当方法结束时变量就消失了。这就是为什么你 return 东西。

在调用方法的地方,可以将方法的结果赋值给新的变量。

因为你 return 一个元组,你可以在赋值时有 2 个变量:

x, y = even_odd_split(Dic1)

或者,如果您想再次使用相同的名字

even, odd = even_odd_split(Dic1)

这是完整的代码。仔细阅读并尝试理解这些名称的含义。请注意,它们在方法内外是不同的。

def even_odd_split(numbers):
    even_numbers = []
    odd_numbers = []
    for sublist in numbers.values():
        for x in sublist:
            if x % 2 == 0:
                even_numbers.append(x)
            else:
                odd_numbers.append(x)
    return even_numbers, odd_numbers


Dic1 = {"N1": [1, 3, 7, 6, 10],
        "N2": [2, 3, 9, 10, 21, 36],
        "N3": [4, 6, 5, 12, 24, 35],
        "N4": [0, 3, 14, 15, 16, 18]
        }

even, odd = even_odd_split(Dic1)
print(f'Even items: {even}\nOdd items: {odd}')

with open("odd.txt", "w") as f:
    f.write(str(odd))

with open("even.txt", "w") as f:
    f.write(str(even))