python: remove element from a list (5)
Abstract: consider remove elements from a list
pop() is used for remove the last element from a list
>>> l
[1, 1, 2, 3, 4, 5, 6, 7, 8]
>>> l.pop()
8
>>> l
[1, 1, 2, 3, 4, 5, 6, 7]
remove() is used for removing a given element from a list. The below is remove the first element equal to 1.
>>> l.remove(1)
>>> l
[1, 2, 3, 4, 5, 6, 7]
>>> l
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> l.remove('4')
>>> l
['0', '1', '2', '3', '5', '6', '7', '8', '9']
del() can remove an element based on its index, or multiple elements.
>>> l
['0', '1', '2', '3', '5', '6', '7', '8', '9']
>>> del l[4] #remove the fifth element
>>> l
['0', '1', '2', '3', '6', '7', '8', '9']
>>> l
['0', '1', '2', '3', '6', '7', '8', '9']
>>> del l[6:] # delete all element from the sixth
>>> l
['0', '1', '2', '3', '6', '7']
Remove all elements meeting a given conditions from a list. The below is to remove all 'a'.
>>> l
['dasf', 'a', 'a34', 'bfthjjuy', 'z']
>>> [x for x in l if 'a' in x] #select all elements containing 'a'
['dasf', 'a', 'a34']
>>> [x for x in l if 'a' not in x] # remove all elements containing 'a'
['bfthjjuy', 'z']
filter() can also work well on removing elements:
>>> filter(lambda x: 'a' in x,l)
['dasf', 'a', 'a34']
Remove duplicates from a list. The codes below give two approach.
class array:
def __init__(self, array):
self.list=array
self.list_len=len(self.list)
#remove duplicates
def remove_duplicate1(self):
unique=[]
duplicate=[]
while len(self.list)>0:
x=self.list.pop()
if x in duplicate:
pass
else:
if x in unique:
unique.remove(x)
duplicate.append(x)
else:
unique.append(x)
print unique
print duplicate
return unique
#remove duplicates
def remove_duplicate2(self):
x=0 #index of unique boundary
y=self.list_len # index of duplicate boundary
while x<y:
A=self.list[x]
#print A, self.list
dup=[x]
for i in range(x+1, y):
if self.list[i]==A:
dup.append(i)
#
if len(dup)==1:
x+=1
else:
#swithch index if there are duplicates
for d in dup[::-1]:
y=y-1
self.list[d],self.list[y]=self.list[y],self.list[d]
#print self.list, '\n'
print 'unique:', self.list[:x]
print 'duplicates:', self.list[y:]
return self.list[:x]
No comments:
Post a Comment