简体   繁体   中英

delete items at the same position (index) from two synchronized lists?

I have two lists:

l1 = ['#', '1', '#', '!']
l2 = ['S', 'T', 'K', 'M']

If there is a '#' in l1 I want to remove it, and remove whatever is at the same position in l2. This is what I have tried (among several other things):

for i in range(len(li[j])):
    for k in range(len(l2[n])):
        if j == "#":
            li.remove([j][i])
            l2.remove([n][k])

But it complains that j is not defined. I want the outcome to look like this:

l1 = ['1', '!']
l2 = ['T', 'M']

I would be grateful for suggestions!

>>> l1 = ['#', '1', '#', '!']
>>> l2 = ['S', 'T', 'K', 'M']

>>> l1,l2 = zip(*((x,y) for x,y in zip(l1,l2) if x!='#'))
>>> l1
('1', '!')
>>> l2
('T', 'M')  

Using filter

>>> l1,l2 = zip(*filter(lambda x: '#' not in x,zip(l1,l2)))
>>> l1
('1', '!')
>>> l2
('T', 'M')

Using itertools

>>> from itertools import compress
>>> l1,l2 = zip(*compress(zip(l1,l2),(x!='#' for x in l1)))
>>> l1
('1', '!')
>>> l2
('T', 'M')

Here is a simple and easy to understand method:

a = ["#", "1", "#", "2", "3", "#"]
b = ["a", "b", "c", "d", "e", "f"]

a,b = zip(*[[a[i], b[i]] for i in range(len(a)) if a[i]!="#"])
print a
print b

Personally I find it much simplier to understand and more effective (read: "faster") than the method @jamylak proposed.

Output:

>>> 
('1', '2', '3')
('b', 'd', 'e')

As you always access the same index in both lists one loop is enough, however you need to be careful when the lists are not of the same length.

Moreover removing from a list while iterating over it is error-prone, the following solution stores all indices in a removal-list and will remove the index from both lists in a second go:

l1 = ['#', '1', '#', '!']    
l2 = ['S', 'T', 'K', 'M']
remove = []
for i in range(len(l1) - 1):
    if l1[i] == '#':
        remove.insert(0, i)

for i in remove:
    l1.pop(i)
    l2.pop(i)

for i in l1:
    print i
for i in l2:
    print i

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM