清理我的清单
你好,我有一个循环,它会计算 MySQL 数据库中的不同记录,然后将数字保存到列表中。这是列表:
<代码>[1L、2L、2L、5L、4L、1L、1L、1L、3L、1L、1L、2L、2L、3L、3L、1L、2L、4L、2L、1L、3L、1L、2L、 4L、1L、2L、1L、1L、3L、1L、3L、1L、5L、2L、1L、1L、5L、1L、1L、1L、4L、2L、1L、3L、2L、1L、2L、2L、 2L、3L、1L、1L、3L、2L、2L、1L、3L、1L、1L、1L、1L、1L、1L、1L、1L、1L、2L、1L、1L、1L、1L、2L、1L、 3L, 3L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L]
现在我浏览这个列表,我只想留下单个数字(意味着 1L,2L 等)我使用此循环:
for number in legend:
print number # to check what number it does currently
counter = legend.count(number)
while counter > 1:
legend.remove(number)
counter -= 1
然后我看到它检查 1,2,3,4,3,2,1 ...这是为什么?为什么这个循环不检查数字 5?最后的列表如下所示:[5L, 5L, 5L, 4L, 3L, 2L, 1L]
这意味着它可以工作,但为什么它不适合数字 5?
提前谢谢
Hello I have a loop which goes counts different records in my MySQL database and then saves the numbers to a list. Here is the list:[1L, 2L, 2L, 5L, 4L, 1L, 1L, 1L, 3L, 1L, 1L, 2L, 2L, 3L, 3L, 1L, 2L, 4L, 2L, 1L, 3L, 1L, 2L, 4L, 1L, 2L, 1L, 1L, 3L, 1L, 3L, 1L, 5L, 2L, 1L, 1L, 5L, 1L, 1L, 1L, 4L, 2L, 1L, 3L, 2L, 1L, 2L, 2L, 2L, 3L, 1L, 1L, 3L, 2L, 2L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 3L, 3L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L]
now I go thru this list and I want to leave only single numbers (means 1L, 2L etc) I'm using this loop:
for number in legend: print number # to check what number it does currently counter = legend.count(number) while counter > 1: legend.remove(number) counter -= 1
then I see that it checks 1,2,3,4,3,2,1 ...why is that? why this loop wont check number 5? at the end the list looks like this:[5L, 5L, 5L, 4L, 3L, 2L, 1L]
that means it works but why it doesn't go for number 5?
thx in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将其放入
集合
中即可。这将自动过滤掉所有重复项。也许您甚至可以跳过该列表,然后将其放在
set
中。Just put it in a
set
.This will automatically filter out all duplicates. Maybe you can even skip the list, and put it in a
set
in the first place.您可能会遇到以下问题:
它给出输出:
List is modded in loop,并且在删除已经循环遍历的某些元素时,您跳过列表中的一个元素。
You might fall into problem such as:
which gives output:
List is modified in loop and while removing some element that you already looped through you are skipping one element in list.