【问题标题】:How to delete odd and even numbers from the list in Python [duplicate]如何从 Python 列表中删除奇数和偶数 [重复]
【发布时间】:2022-12-17 08:02:37
【问题描述】:

完成此任务后,我意识到它没有正确执行,因为偶数和奇数仍保留在列表中。如何解决此错误? 或者有谁知道如何在这种情况下替换 for 循环 for while 循环

  1. 写一些代码从 list3 中删除任何偶数
  2. 写一些代码从 list2 中删除任何奇数

list1 = ["\nroll", "burger", "cheese", "ketchup", "mustard"]
list2 = []
list3 = []

a = 0
while a < 10:
 a = a + 1
 userdata = input("Enter a whole number: ")
 usernum = int(userdata)
 list2.append(usernum) 

print (*list1, sep="\n")
list3 = list2.copy()

#remove even
print ("list3",list3)
for i in list3:
    div = i%2
    if div == 0:
        list3.remove(i)
print("remove even, list3",list3)


#remove odd
for x in list2:
    div = x%2
    if div != 0:
        list2.remove(x)
print("remove odd, list2", list2)

【问题讨论】:

    标签: python for-loop while-loop


    【解决方案1】:

    在遍历列表时改变列表是一个很大的禁忌。使用您需要的项目重新创建它可能更容易:

    list2 = [x for x in list2 if x % 2 == 0]
    list3 = [x for x in list3 if x % 2 != 0]
    

    【讨论】:

      【解决方案2】:

      您应该使用列表理解:

      list3_cleaned = [x for x in list3 if x % 2 != 0]
      list2_cleaned = [x for x in list2 if x % 2 == 0]
      

      这样您就不会在遍历列表时编辑列表。

      【讨论】:

        猜你喜欢
        • 2017-02-06
        • 1970-01-01
        • 1970-01-01
        • 2017-02-02
        • 1970-01-01
        • 2019-03-19
        • 2019-12-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多