擅长:python、mysql、java
<pre><code>a=[('H40T','H04H'), ('Z40A','H04T'), ('M90K','H04B'), ('H40H','H04B'), ('H40A','A04B'), ('A40T','Q04Q'), ('H40T','H04H'), ('Z40A','L04M'), ('A03C','H04T'), ('H40T','H04B'), ('H40A','A04B'), ('H40T','Q04C')]
desire=['H04B','H04T','H04H']
remove_lst=[]
for idx,counter in enumerate(b):
if all([d not in counter for d in desire]):
remove_lst.append(counter)
# print('removed',counter)
new_list = [el for el in b if el not in remove_lst]
print(len(new_list))
new_list
</code></pre>
<p>例如:</p>
<pre><code>b=[1,2,3,3,4,5]
for idx,el in enumerate(b):
print(idx,el)
if el==3:
b.remove(el)
</code></pre>
<p>输出为:</p>
<pre><code>0 1
1 2
2 3
3 4
4 5
</code></pre>
<p>因为当你遍历一个列表并删除一个元素时,它会跳过下一个元素,因为它会遍历已删除元素的更新列表</p>
<p>一种方法可能是使用列表的副本,或者在之后删除元素,就像上面的代码或集合是解决这个问题的好方法一样。你知道吗</p>
<pre><code>b=[1,2,3,3,4,5]
c=b.copy()
for el in c:
print(el)
if el==3:
b.remove(el)
</code></pre>