[英]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))
嘗試下面的代碼,您會發現-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.