Re: [问题] not in 检查list元素会失败吗?

楼主: abc2090614 (casperxdd)   2018-12-26 11:42:44
※ 引述《ofspring (青春无敌)》之铭言:
: 我想做两个list_A, list_B 元素的确认
: 然后用 list_A.remove() 移除掉不在list_B
: 最后的目标是让list_A, list_B 相同
: 我的程式码如下
: (python ver 3.6.6, MacOS, 用colab和jupyter notebook跑都是一样的结果)
原因就跟推文说的一样
在for里面的位置被移动了
把 code 加上一点东西印出来
list_A = ["a", "b", "c","g", "f", "K", "larry", "curly", "moe"]
list_B = ["a", "b", "c","g", "f", "K"]
for index, element in enumerate(list_A):
print(index, element)
if element not in list_B:
list_A.remove(element)
得到的结果是
0 a
1 b
2 c
3 g
4 f
5 K
6 larry
7 moe
也就是在6移掉 "larry" 之后, 在7的位置变成 moe 所以剩一个curly
一般在两个 list 切来切去会直接创一个新 list 而不会用.remove
https://twitter.com/raymondh/status/1055478808793546752
@raymondh
Q. What are the best practices for modifying a list while looping over it?
A. Don't.
Seriously, just make a new list and avoid hard-to-read code with hard-to-find
bugs.
我应该会这样写
new_list = [_ for _ in list_A if _ in list_B]
作者: ofspring (青春无敌)   2018-12-26 18:06:00
"Don't." XD 你的解法更直观更快!刚刚CD无法按推文,解法漂亮补推一个

Links booklink

Contact Us: admin [ a t ] ucptt.com