>>> somelist = range(10)>>> for x in somelist:... somelist.remove(x)>>> somelist[1, 3, 5, 7, 9]
>>> somelist = range(10)>>> for x in somelist[:]:... somelist.remove(x)>>> somelist[]
newlist = []for tup in somelist:# lots of code here, possibly setting things up for calling determineif determine(tup):newlist.append(tup)somelist = newlist
inlist = [{'field1':10, 'field2':20}, {'field1':30, 'field2':15}]for idx, i in enumerate(inlist):do some stuff with i['field1']if somecondition:xlist.append(idx)for i in reversed(xlist): del inlist[i]
list_len = len(some_list)for i in range(list_len):reverse_i = list_len - 1 - icur = some_list[reverse_i]
# some logic with cur element
if some_condition:some_list.pop(reverse_i)
>>> words = ['cat', 'window', 'defenestrate']>>> for w in words[:]: # Loop over a slice copy of the entire list.... if len(w) > 6:... words.insert(0, w)...>>> words['defenestrate', 'cat', 'window', 'defenestrate']
from fluidIter import FluidIterablefSomeList = FluidIterable(someList)for tup in fSomeList:if determine(tup):# remove 'tup' without "breaking" the iterationfSomeList.remove(tup)# tup has also been removed from 'someList'# as well as 'fSomeList'
from fluidIter import FluidIterablel = [0,1,2,3,4,5,6,7,8]fluidL = FluidIterable(l)for i in fluidL:print('initial state of list on this iteration: ' + str(fluidL))print('current iteration value: ' + str(i))print('popped value: ' + str(fluidL.pop(2)))print(' ')
print('Final List Value: ' + str(l))
这将产生以下产出:
initial state of list on this iteration: [0, 1, 2, 3, 4, 5, 6, 7, 8]current iteration value: 0popped value: 2
initial state of list on this iteration: [0, 1, 3, 4, 5, 6, 7, 8]current iteration value: 1popped value: 3
initial state of list on this iteration: [0, 1, 4, 5, 6, 7, 8]current iteration value: 4popped value: 4
initial state of list on this iteration: [0, 1, 5, 6, 7, 8]current iteration value: 5popped value: 5
initial state of list on this iteration: [0, 1, 6, 7, 8]current iteration value: 6popped value: 6
initial state of list on this iteration: [0, 1, 7, 8]current iteration value: 7popped value: 7
initial state of list on this iteration: [0, 1, 8]current iteration value: 8popped value: 8
Final List Value: [0, 1]
fluidArr = FluidIterable([0,1,2,3])# get iterator first so can query the current indexfluidArrIter = fluidArr.__iter__()for i, v in enumerate(fluidArrIter):print('enum: ', i)print('current val: ', v)print('current ind: ', fluidArrIter.currentIndex)print(fluidArr)fluidArr.insert(0,'a')print(' ')
print('Final List Value: ' + str(fluidArr))
randInts = [70, 20, 61, 80, 54, 18, 7, 18, 55, 9]fRandInts = FluidIterable(randInts)fRandIntsIter = fRandInts.__iter__()# for each value in the list (outer loop)# test against every other value in the list (inner loop)for i in fRandIntsIter:print(' ')print('outer val: ', i)innerIntsIter = fRandInts.__iter__()for j in innerIntsIter:innerIndex = innerIntsIter.currentIndex# skip the element that the outloop is currently on# because we don't want to test a value against itselfif not innerIndex == fRandIntsIter.currentIndex:# if the test element, j, is a multiple# of the reference element, i, then remove 'j'if j%i == 0:print('remove val: ', j)# remove element in place, without breaking the# iteration of either loopdel fRandInts[innerIndex]# end if multiple, then remove# end if not the same value as outer loop# end inner loop# end outerloop
print('')print('final list: ', randInts)
alist = ['good', 'bad', 'good', 'bad', 'good']i = 0for x in alist[:]:if x == 'bad':alist.pop(i)i -= 1# do something cool with x or just print xprint(x)i += 1
>>> L1 = [(1,2), (5,6), (-1,-2), (1,-2)]>>> for (a,b) in L1:... if a < 0 or b < 0:... L1.remove(a,b)...Traceback (most recent call last):File "<stdin>", line 3, in <module>TypeError: remove() takes exactly one argument (2 given)
L2 = L1for (a,b) in L1:if a < 0 or b < 0 :L2.remove((a,b))# Now, remove the original copy of L1 and replace with L2print L2 is L1del L1L1 = L2; del L2print ("L1 is now: ", L1)
import copyL1 = [(1,2), (5,6),(-1,-2), (1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]L2 = copy.copy(L1)for (a,b) in L1:if a < 0 or b < 0 :L2.remove((a,b))# Now, remove the original copy of L1 and replace with L2del L1L1 = L2; del L2>>> L1 is now: [(1, 2), (5, 6), (3, 4), (5, 7), (2, 1), (0, 6)]
最后,有一个比创建一个全新的L1副本更干净的解决方案。反向()函数:
L1 = [(1,2), (5,6),(-1,-2), (1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]for (a,b) in reversed(L1):if a < 0 or b < 0 :L1.remove((a,b))print ("L1 is now: ", L1)>>> L1 is now: [(1, 2), (5, 6), (3, 4), (5, 7), (2, 1), (0, 6)]
""" Sieve of Eratosthenes """
def generate_primes(n):""" Generates all primes less than n. """primes = list(range(2,n))idx = 0while idx < len(primes):p = primes[idx]for multiple in range(p+p, n, p):try:primes.remove(multiple)except ValueError:pass #EAFPidx += 1yield p
我可以想到三种方法来解决你的问题。例如,我将创建一个随机元组列表somelist = [(1,2,3), (4,5,6), (3,6,6), (7,8,9), (15,0,0), (10,11,12)]。我选择的条件是sum of elements of a tuple = 15。在最终列表中,我们将只有总和不等于15的元组。
newlist1 = [somelist[tup] for tup in range(len(somelist)) if(sum(somelist[tup])!=15)]
print newlist1>>>[(1, 2, 3), (7, 8, 9), (10, 11, 12)]
方法3.>找到满足给定条件的索引,然后使用与这些索引对应的删除元素(元组)。以下是其代码。
indices = [i for i in range(len(somelist)) if(sum(somelist[i])==15)]newlist2 = [tup for j, tup in enumerate(somelist) if j not in indices]
print newlist2>>>[(1, 2, 3), (7, 8, 9), (10, 11, 12)]