0

lis a list that I want to explore in order to suppress some items. The function do.i.want.to.suppres.i returns TRUE or FALSE in order to tell me whether I want the suppression. The details of this function is not important.

I tried this:

l = [1,4,2,3,5,3,5,2]
for i in l:
   if do.i.want.to.suppress.i(i):
      del i
print l

but l does not change! So I tried

l = [1,4,2,3,5,3,5,2]
for position,i in enumerate(l):
   if do.i.want.to.suppress.i(i):
      del l[position]

But then the problem is that the position does not match the object i as lget modified during the loop.

I could do something like this:

l = [1,4,2,3,5,3,5,2]
for position,i in enumerate(l):
   if do.i.want.to.suppress.i(i):
      l[position] = 'bulls'
l = [x for x in l if x!='bulls']

But I guess there should have a smarter solution. Do you have one?

4

5 回答 5

5
l = [item for item in my_list if not do_I_suppress(item)]

列出理解!学习他们!爱他们!住他们!

于 2013-08-26T17:19:10.823 回答
1

列表理解方法是最 Pythonic 的方法,但如果你真的需要修改列表本身,那么我发现这是最好的方法,比 while 循环方法更好:

for position in xrange(len(l) - 1, -1, -1):        
    i = l[position]
    if do.i.want.to.suppress.i(i):
        del l[position]
于 2013-08-26T17:23:11.897 回答
0

除了列表理解(返回一个列表,在内存中创建完整列表):

filtered_list = [itm for itm in lst if i_want_to_keep(itm)]

您可以使用filter()(与 List Comprehensions 相同的结果)

filtered_list = filter(i_want_to_keep, lst)

itertools.ifilter()(它返回一个迭代器并避免在内存中创建整个列表,对迭代特别有用)

import itertools
filtered_list = itertools.ifilter(i_want_to_keep, lst)

for itm in filtered_list:
    do_whatever(itm)
于 2013-08-26T17:33:21.693 回答
0

这是使用 while 循环的好地方

i = 0
while i < len(l):
  if do.i.want.to.suppress.i(i):
    del l[i]
  else:
    i = i + 1
于 2013-08-26T17:19:00.687 回答
0

filter也将起作用:

answer = filter(lambda x: not do_I_suppress(x), lis)

请注意,在 Python 3.x 中,您需要filter输入list

answer = list(filter(lambda x: not do_I_suppress(x), lis))
于 2013-08-26T17:24:27.607 回答