【问题标题】:All elements aren't appearing when iterating through a loop [duplicate]遍历循环时未出现所有元素[重复]
【发布时间】:2021-03-15 22:37:39
【问题描述】:

我的学校作业要求我从用户那里读取一个列表,然后从中删除所有奇怪的元素。我用来检查奇数的循环甚至不会遍历所有列表元素。

ans=1
lst=[]
while ans!=0:
    no=int(input('Enter value for list or press 0 to exit:'))
    if no!=0:
        lst.append(no)
    else:
        break

print('\nYour list is:',lst)

       
for i in lst:     # loop to check for odd nos
    print('i is', i)
    if i%2==1:
        lst.remove(i)

print('List after removing odd elements:',lst)

在第二个循环中,我添加了 print 语句来检查不一致的输出,结果如下: Output

某些列表元素在迭代时被跳过(?),因此它们没有被删除,这给了我不正确的输出。为什么会发生这种情况?

【问题讨论】:

标签: python python-3.x list for-loop


【解决方案1】:

创建一个新列表(分配给 lst)并选择元素 回复:elm%2 != 1

lst = [i for i in lst if i%2 != 1] #There will be no prints

有印刷品:

new_lst = []
for i in lst:
    print("i is ", i)
    if i%2 != 1:
       new_lst.append(i)
lst = new_lst

也可以:

lst = list(filter(
    lambda x:( x % 2 ! = 1), #Each elements of lst is passed to this func
    lst                      #is the output of func is True (not 0) => add to list
))

【讨论】:

    【解决方案2】:

    首先,您只读取数字。 其次,由于我们确定我们有一个数字,如果它不是偶数,我们不需要添加这个数字。读取用户输入,直到他们输入 -1

        list_even = []
        while True:
            try:
                digit = int(input('Enter value digit: '))
                if digit == -1: break
                elif digit % 2 == 0:
                    list_even.append(digit)
            except ValueError:
                print('error is not digit')
                pass
        print('evens: ', list_even)
    

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 2019-06-24
      • 2011-10-31
      • 2017-04-29
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      相关资源
      最近更新 更多