I have two lists:
list_a = [1,5,8]
list_b = [12,4,2,5,7,5,3,6,8]
The elements in list_a correspond to the indices of elements in list_b. Both lists are of size greater than 100.
How can I delete the elements of list_b whose indices are in list_a,
so if you take the lists above the resulting list is [12,2,5,7,3,6]?
Two options:
Create a new list with a list comprehension:
newlist = [el for i, el in enumerate(oldlist) if i not in indices_to_delete]
This will be all the faster if indices_to_delete was a set:
indices_to_delete = set(indices_to_delete)
newlist = [el for i, el in enumerate(oldlist) if i not in indices_to_delete]
because membership testing in a set is O(1) vs. O(n) in a list.
Remove the indices in reverse-sorted order from the list in-place:
for index in sorted(indices_to_delete, reversed=True):
del oldlist[index]
If you don't remove items in reverse sorted order, items with higher indices are moved up as items with lower indices are removed and the rest of your indices_to_delete no longer match the items you needed to remove.
This should accomplish that:
for delidx in reversed(toDelete):
del otherList[delidx]
Also, using a list comprehension:
l2 = [elem for i, elem in enumerate(l1) if i not in toDelete]
now that I understand the question
a = numpy.array(list2)
mask = [True]*len(a)
mask[list1] = False
print a[mask]
Ok, this a slightly over-engineered solution, but here it is
def get_newl(li, index):
index = sorted(index, reverse=True)
i=0
while i < (len(li)-len(index)):
x = index.pop()
while i < x:
yield li[i]
i+=1
i+=1
Run the code here http://codebunk.com/bunk#-Isxeb4TZOHBCvQi4EsY
Related
I want to remove some items from specific places. for example, I have list [a,b,c,d,e,f,g,h,i]. the number of items in this list constantly changes.
That is why I need special method that is helps to remove items from same place. Now the modified list should be like that: list [a,b,c,d,e,f,i]. g and h should always be removed.
Do you want to remove the second- and third-last item from the list?
This can be achieved like this:
del lst[-3:-1]
If you create dictionaries with necessary indexes you can use them to create a new list.
lst = ['a','b','c','d','e','f','g','h','i']
other = ['a','y','b','c','d','e','g','h','l']
indexed_lst = {i: item for i, item in enumerate(lst)}
indexed_other = {i: item for i, item in enumerate(other)}
[item for i, item in indexed_lst.items() if indexed_lst.get(i, None) != indexed_other.get(i, None) ]
You can remove from the list either by index or by value. In either case it is a good practice to check if the index/value is present in the list. As for removing an item from the list you could use one of the below based on what info is available / output required.
Remove an item by index and get its value: pop()
# where i is the index of the value to be removed
if i < len(lst)
result = l.pop(i)
Remove items by index or slice: del()
# where i is the index of the value to be removed
if i < len(lst) :
lst.del(i)
Remove an item by value: remove()
# where `h` is the value to be removed
if 'h' in lst:
lst.remove('h')
You could also remove items from a list based on a given condition, in which case you could use list comprehensions
l = list(range(10))
# Remove all the odd numbers
print([i for i in l if i % 2 != 0])
ahh i understand your answer, if you use index like this
Remove items by index, specific place
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for index,item in enumerate(lst) if index != 6 and index != 7]
print(lst)
or Remove items by Value
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for item in lst if item != 'g' and item != 'h']
print(lst)
Use the .pop() to pop off any given index off the list
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for item in lst if item != 'g' and item != 'h']
print(lst)
if you have more input, tell me
I have a list of lists, and I want to make a function that checks if each of the lists inside have exactly one item in common with all the other lists, if so return True.
Couldn't make it work, is there a simple way to do it without using modules?
I've tried something like this:
list_of_lists = [['d','b','s'],['e','b','f'],['s','f','l'],['b','l','t']]
new_list = []
for i in list_of_lists:
for item in i:
new_list.append(item)
if len(set(new_list)) == len(new_list)-len(list_of_lists):
return True
if you want to intersect all the items in the sublist you can convert them to a set and find intersection check if its an empty set.
list_of_lists = [['d','b','s'],['e','b','f'],['s','f','l'],['b','l','t']]
common_items = set.intersection(*[set(_) for _ in list_of_lists])
if len(common_items) == 1:
return True
return False
Using list comprehension:
def func(list_of_lists):
return sum([all([item in lst for lst in list_of_lists[1:]]) for item in list_of_lists[0]]) == 1
Works if each is guaranteed for one of each item. Also if its not, returns True only if there is one match.
use the Counter after joining a list and a compare list to determine occurrences. Ensure at least one item in the resulting list has a frequency of 2.
from collections import Counter
list_of_lists = [['d','b','s'],['e','b','f'],['s','f','l'],['b','l','t']]
for i in range(len(list_of_lists)):
for j in range(i+1,len(list_of_lists)):
result=(list_of_lists[i]+list_of_lists[j])
counts=(Counter(result))
matches={x for k,x in counts.items() if x==2}
if len(matches)==0:
print("missing a match")
I just want to get those with the index that is a multiple of two
code=[1,2,4,7,2,6,8]
ncode=[code[i] for i%2==0]
Just use this indexing method:
code[::2]
If you want the odd index
code[1::2]
Generally, this is how it works:
seq = L[start:stop:step]
seq = L[::2] # get every other item, starting with the first
seq = L[1::2] # get every other item, starting with the second
You can use list comprehensions this way :
code=[1,2,4,7,2,6,8]
print [val for i,val in enumerate(code) if i%2==0]
enumerate() returns the index and value at the index, which is stored in i and value respectively.
For more details:
list comprehension
enumerate
code = [1,2,4,7,2,6,8]
new_code = []
for i in range(0, len(code), 2): ### iterate over even indexes
new_code.append(code[i])
print new_code
I have two quite long lists and I know that all of the elements of the shorter are contained in the longer, yet I need to isolate the elements in the longer list which are not in the shorter so that I can remove them individually from the dictionary I got the longer list from.
What I have so far is:
for e in range(len(lst_ck)):
if lst_ck[e] not in lst_rk:
del currs[lst_ck[e]]
del lst_ck[e]
lst_ck is the longer list and lst_rk is the shorter, currs is the dictionary from which came lst_ck. If it helps, they are both lists of 3 digit keys from dictionaries.
Use sets to find the difference:
l1 = [1,2,3,4]
l2 = [1,2,3,4,6,7,8]
print(set(l2).difference(l1))
set([6, 7, 8]) # in l2 but not in l1
Then remove the elements.
diff = set(l2).difference(l1):
your_list[:] = [ele for ele in your_list of ele not in diff]
If you lists are very big you may prefer a generator expression:
your_list[:] = (ele for ele in your_list of ele not in diff)
If you don't care of multiple occurrences of the same item, use set.
diff = set(lst_ck) - set(lst_rk)
If you care, try this:
diff = [e for e in lst_rk if e not in lst_ck]
I have a list, e.g.
l = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']
How can I get all the elements in the list before the occurrance of the longest element and not the ones that come after?
This is one way:
l = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']
new_list = l[:l.index(max(l, key=len))]
This works:
lst = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']
idx, maxLenStr = max(enumerate(lst), key=lambda x:len(x[1]))
sublist = lst[:idx]
It only iterates through the list once for determining the maximum length, whereas using max() and then index() iterates twice over all the elements. It also stores the string with the maximum length in maxLenStr and the index where it was found in idx, just in case.