[英]Removing all values bigger than desired number from the list
L=[10,19,20,30,8,11,9]
i=0
while i==0:
while L[i]<=12:
i+=1
else:
L.pop(i)
i=0
Hello, I want to remove values, which are bigger than 12, from the list.您好,我想从列表中删除大于 12 的值。 I get the list I want, but I also get an error message, which says "list index out of range" even though I make i=0 at the end of loop.
我得到了我想要的列表,但我也收到了一条错误消息,上面写着“列表索引超出范围”,即使我在循环结束时使 i=0。 How can I fix it?
我该如何解决?
You can do, using a conditional list comprehension :您可以使用条件列表理解:
l=[each for each in L if each<=12]
l
will be: l
会:
[10, 8, 11, 9]
If you don't like list comprehension, you can do:如果你不喜欢列表理解,你可以这样做:
l=[]
for each in L:
if each<=12:
l.append(each)
l
will be the same as before. l
会和以前一样。
A solution with while and without creating a new list一个无需创建新列表的解决方案
L=[10,19,20,30,8,11,9]
i=0
while i < len(L):
if L[i] > 12:
L.pop(i)
else:
i += 1
When you do a pop()
, you are changing the list by shortening it.当您执行
pop()
,您通过缩短列表来更改列表。 If you want to do the pop()
call, I suggest parsing the list in reverse order, starting at the end and working towards the beginning.如果你想做
pop()
调用,我建议以相反的顺序解析列表,从末尾开始,从头开始。
for i in range(len(L) - 1, -1, -1):
if L[i] > 12:
L.pop(i)
But, to directly answer your question, change your code to replace:但是,要直接回答您的问题,请更改您的代码以替换:
L.pop(i)
with:和:
if i < len(L):
L.pop(i)
That should make your actual error go away.那应该会使您的实际错误消失。 But it's not the best way to handle the problem.
但这不是处理问题的最佳方法。 I would still suggest processing the list in reverse order.
我仍然建议以相反的顺序处理列表。
You can use filter
:您可以使用
filter
:
L=[10,19,20,30,8,11,9]
#For python 2
L1 = filter(lambda x: x < 12, L)
#For python 3, wrap filter with list
L1 = list(filter(lambda x: x < 12, L))
print (L1)
though this is not the best way of doing it, but it may be the desired fix you are looking for虽然这不是最好的方法,但它可能是您正在寻找的理想修复
L=[10,19,20,30,8,11,9]
i=0
while i==0:
while L[i]<=12:
if i==len(L)-1:
break
i+=1
else:
L.pop(i)
i=0
Try pandas
for simpler answer尝试
pandas
以获得更简单的答案
import pandas as pd
df = pd.DataFrame({'A': [10,19,20,30,8,11,9]})
final_list = df[df['A'] <= 12]['A'].values.tolist()
Simplest answer最简单的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.