【问题标题】:Removing specific index from list while iterating / improving nested loops在迭代/改进嵌套循环时从列表中删除特定索引
【发布时间】:2019-04-17 06:21:59
【问题描述】:

我处于有 3 个嵌套循环的情况。每 x 次迭代,我想重新启动第二个 for 循环。 如果第三个 for 循环中的元素满足某个条件,我想从列表中删除该元素。

我不确定如何实现这一点,并且根据我阅读的类似问题,使用列表理解或创建新列表不会真正起作用。

示例伪代码:

items_of_interest = ["apple", "pear"]

while True: # restart 10,000 iterations (API key only last 10,000 requests)
    api_key = generate_new_api_key()
    for i in range(10000):
        html = requests.get(f"http://example.com/{api_key}/items").text
        for item in items_of_interest:
            if item in html:
                items_of_interest.remove(item)

原始代码要大得多,需要进行大量检查,不断地解析 API 以获取某些东西,而且你可以看出它的组织有点混乱。我不确定如何降低复杂性。

【问题讨论】:

  • 你在itemfound之后使用break
  • @hansolo 如果items_of_interest 中可能存在多个项目匹配项,则不一定要匹配

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


【解决方案1】:

在不了解全貌的情况下,很难说哪种方法是最佳的。无论如何,这是使用理解的一种方法。

items_of_interest = ["apple", "pear"]

while True: # restart 10,000 iterations (API key only last 10,000 requests)
    api_key = generate_new_api_key()
    for i in range(10000):
        html = requests.get(f"http://example.com/{api_key}/items").text

        # Split your text blob into separate strings in a set
        haystack = set(html.split(' '))
        # Exclude the found items!
        items_of_interest = list(set(items_of_interest).difference(haystack))

【讨论】:

  • 即将写一个类似的答案,但有一点不同:使用difference 而不是intersection 并完全避免列表理解怎么样?
  • @Francesco 这已经不是习惯了!我几乎一直使用intersection。如果您不介意,我会更新我的答案以使用difference
  • 请。我喜欢你用更少的嵌套和更多的声明风格来简化代码
  • 作为 OP 的建议,如果您选择此实现,您应该首先考虑将 items_of_interest 定义为一个集合
  • @Francesco 我保留了这一点,因为它在 OP 的问题中是这样定义的 :)
【解决方案2】:

它的工作原理与您的建议非常相似。相关的关键字是del。例如

>>> x = range(5)
>>> for i in ['a','b','c']:
...     print ('i:' + str(i) )
...     for j in x:
...         print('j:' + str(j))
...     if j == 3:
...             del x[j]
...
i:a
j:0
j:1
j:2
j:3
i:b
j:0
j:1
j:2
j:4
i:c
j:0
j:1
j:2
j:4

3 已从列表 x 中删除以供以后的通行证使用。

另请参阅 Python doco https://docs.python.org/3.7/tutorial/datastructures.html 和诸如 Difference between del, remove and pop on lists 之类的答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多