In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail the example analysis of deleting projects from the python iterative list. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Question:
There is this code:
Numbers = range (1,50) for i in numbers: if I
< 20: numbers.remove(i) print(numbers) 但得到的结果是: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49] 当然,希望低于 20 的数字不会出现在结果中。看起来在删除时做错了什么。 解决方法 在迭代列表时正在修改列表。这意味着第一次通过循环,i == 1,所以1从列表中删除。然后for循环转到列表中的第二项,它不是2,而是 3!然后从列表中删除它,然后for循环继续到列表中的第三项,现在是 5。依此类推。也许像这样更容易形象化,用 ^ 指向的值i: [1, 2, 3, 4, 5, 6...] ^ 这就是列表最初的状态;然后 1 被删除,循环转到列表中的第二项: [2, 3, 4, 5, 6...] ^[2, 4, 5, 6...] ^ 等等。 在迭代列表时没有改变列表长度的好方法。你能做的最好的事情是这样的: numbers = [n for n in numbers if n >= 20]
Or this, for in-place changes (what is in parentheses is a generator expression that is implicitly converted to a tuple before a slice assignment):
Numbers [:] = (n for in in numbers if n > = 20)
If you want to operate on n before deleting it, one of the techniques you can try is:
For I, n in enumerate (numbers): if n < 20: print ("do something") numbers [I] = Nonenumbers = [n for n in numbers if n is not None] this is the end of the article on "sample Analysis of deleting items from python iteration list". I hope the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good Please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 256
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.