簡體   English   中英

從兩個同步列表中刪除相同位置(索引)的項目?

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

我有兩個清單:

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

如果l1中有一個“#”,我想將其刪除,然后刪除l2中相同位置的所有內容。 這是我嘗試過的(除其他事項外):

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

但是它抱怨j沒有定義。 我希望結果看起來像這樣:

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

我將不勝感激!

>>> 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')  

使用filter

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

使用itertools

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

這是一個簡單易懂的方法:

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

我個人認為,與@jamylak提出的方法相比,它更容易理解並且更有效(閱讀:“更快”)。

輸出:

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

由於您總是在兩個列表中訪問相同的索引,因此一個循環就足夠了,但是,當列表的長度不相同時,請務必小心。

此外,在遍歷列表時將其從列表中刪除很容易出錯,以下解決方案將所有索引存儲在刪除列表中,並在第二步從兩個列表中刪除該索引:

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