簡體   English   中英

如何從列表中刪除元素

[英]How to remove elements from a list

我有兩個清單

first = ['-6.50', '-7.00', '-6.00', '-7.50', '-5.50', '-4.50', '-4.00', '-5.00'] 
second = ['-7.50', '-4.50', '-4.00']

我想縮短first通過發生在每一個元素second列表。

for i in first:
    for j in second:
        if i == j:
            first.remove(i)

不知道為什么這不能刪除-4.00

['-6.50', '-7.00', '-6.00', '-5.50', '-4.00', '-5.00']

任何幫助表示贊賞:)

>>> first = ['-6.50', '-7.00', '-6.00', '-7.50', '-5.50', '-4.50', '-4.00', '-5.00']
>>> second = ['-7.50', '-4.50', '-4.00']
>>> set_second = set(second) # the set is for fast O(1) amortized lookup
>>> [x for x in first if x not in set_second]
['-6.50', '-7.00', '-6.00', '-5.50', '-5.00']

不要修改您要遍歷的序列。

最簡單的方法:

list(set(first) - set(second))

如果您不關心訂單,請使用

list(set(temp1) - set(temp2))

參考: 獲得兩個列表之間的差異

嘗試下面的代碼,您會發現-4.00並不能並排:

for i in first:
    for j in second:
        print i,j,
        if i == j:
            print 'removed'
            first.remove(i)
        else:
            print
  • 您不應該修改要迭代的序列。

要解決您的問題,只需創建列表的副本即可,只需添加[:]

for i in first[:]:
    for j in second[:]:
        if i == j:
            first.remove(i)

另一種方法是:

[i for i in first if i not in second]
l3 = [x for x in first if x not in second]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM