简体   繁体   English

从两个同步列表中删除相同位置(索引)的项目?

[英]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. 如果l1中有一个“#”,我想将其删除,然后删除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. 但是它抱怨j没有定义。 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 使用filter

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

Using itertools 使用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. 我个人认为,与@jamylak提出的方法相比,它更容易理解并且更有效(阅读:“更快”)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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