【问题标题】:for loop doesn't loop to next element pythonfor循环不会循环到下一个元素python
【发布时间】:2019-05-14 08:00:02
【问题描述】:

我正在尝试遍历列表。但它正在获得第一个元素。它没有得到第二个元素。我无法弄清楚我做错了什么。

filte = ['fingerprint','cipher']
dupe = ['cipher','extract']

for val in filte:
    print(val)
    if val in dupe:
        dupe.remove(val)
    else:
        filte.remove(val)

print("filter",filte)
print("dupe",dupe)

我得到的输出:

fingerprint
filter ['cipher']
dupe ['cipher', 'extract']

需要的输出:

fingerprint
cipher
filter ['cipher']
dupe [ 'extract']

【问题讨论】:

  • 我不完全知道循环在 Python 中是如何工作的,但是当您在循环期间删除一个元素时,它可能会带来一个迭代问题。它正在等待第二个元素,但删除后,cipher 成为第一个元素,因此没有第二个。
  • 没错。所以 OP 你想要么迭代一个反向列表(删除它的最后一个元素不会改变它的索引),要么构建一个新列表,在其中添加合适的元素。
  • 你能解释一下@SmackAlpha你想在这里做什么吗?

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


【解决方案1】:

使用set

例如:

filte = ['fingerprint','cipher']
dupe = ['cipher','extract']

print(list(set(filte) - set(dupe)))  #OR list(set(filte).difference(set(dupe)))
print(list(set(dupe) - set(filte)))

输出:

['fingerprint']
['extract']

注意:在迭代对象时删除元素不是一个好习惯。

【讨论】:

    【解决方案2】:

    只需删除else

    filte = ['fingerprint','cipher']
    dupe = ['cipher','extract']
    
    for val in filte:
        print(val)
        if val in dupe:
            dupe.remove(val)
            filte.remove(val)
    
    print("filter",filte)
    print("dupe",dupe)
    

    输出:

    fingerprint
    cipher
    filter ['fingerprint']
    dupe ['extract']
    

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 1970-01-01
      • 2016-01-26
      • 2020-01-05
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      相关资源
      最近更新 更多