Let say if
# Displaying old and reference in columns for better visual #
old= [2,2,6,6,2,4, 6, 6, 8,2]
reference=[7,1,6,2,4,9,10,16,12,5]
ID=2
What is faster way to remove the variable ID from reference list and delete old[ reference[ID match] ] from the old list?
I happens to developed this solution while asking my question... but is there better way to do this?
def List_Value_Removal(old,reference,ID):
counter=0
new=[]
for test in reference:
if ID!=test:
new.append(old[counter])
checker+=1
return new
Use the zip()
function to pair up the lists, then a list comprehension to only keep values where the reference value does not match ID
:
def List_Value_Removal(old, reference, ID):
return [v for v, ref in zip(old, reference) if ref != ID]
values, references = List_Value_Removal(values, references, some_id)
Demo:
>>> old = [2, 2, 6, 6, 2, 4, 6, 6, 8, 2]
>>> reference = [7, 1, 6, 2, 4, 9, 10, 16, 12, 5]
>>> ID = 2
>>> [v for v, ref in zip(old, reference) if ref != ID]
[2, 2, 6, 2, 4, 6, 6, 8, 2]
If you need to update reference
as well, return two lists:
def List_Value_Removal(old, reference, ID):
return zip(*((v, ref) for v, ref in zip(old, reference) if ref != ID))
Demo:
>>> new, newref = zip(*((v, ref) for v, ref in zip(old, reference) if ref != ID))
>>> new
(2, 2, 6, 2, 4, 6, 6, 8, 2)
>>> newref
(7, 1, 6, 4, 9, 10, 16, 12, 5)
You could also do:
old= [2,2,6,6,2,4,6,6,8,2]
reference=[7,1,6,2,4,9,10,16,12,5]
ID=2
new = [old[i] for i in range(len(old)) if reference[i] != ID]
Just considering both the list are of same length and only one index to remove, btw we can make it more generic :
>>> old = [2,2,6,6,2,4, 6, 6, 8,2]
>>> reference=[7,1,6,2,4,9,10,16,12,5]
>>> id = 2
>>> del old[(reference.index(id))]
>>> old
[2, 2, 6, 2, 4, 6, 6, 8, 2]
>>>
def List_Value_Removal(old,ref, id):
new = old[:]
ind = ref.index(id)
new.pop(ind)
return new
Not sure if there is a particular reason that you are using two arrays? If you used a dict:
ref = {7:2,1:2,6:6,2:6,4:2,9:4,10:6,16:6,12:8,5:2}
You could just:
ref.pop(id)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.