作者ofspring (青春无敌)
看板Python
标题[问题] not in 检查list元素会失败吗?
时间Tue Dec 25 23:41:40 2018
我想做两个list_A, list_B 元素的确认
然後用 list_A.remove() 移除掉不在list_B
最後的目标是让list_A, list_B 相同
我的程式码如下
(python ver 3.6.6, MacOS, 用colab和jupyter notebook跑都是一样的结果)
--
list_A = ["a", "b", "c","g", "f", "K", "larry", "curly", "moe"]
list_B = ["a", "b", "c","g", "f", "K"]
for element in list_A:
if element not in list_B:
list_A.remove(element)
print(list_A)
--
我得到的结果
['a', 'b', 'c', 'g', 'f', 'K', 'curly']
多了一个'curly' @@
想请教板上的高手们,是语法还是哪边出错呢?
1. not in 无法这样使用?
2. remove()的问题?
(把元素换成数字也是有类似的状况)
有尝试把下面的这段独立成一个cell, 执行第二次就完全相同了~
('curly'就成功remove)
--
for element in list_A:
if element not in list_B:
list_A.remove(element)
--
找了stackoverflow一个下午,找不到解答
我该使用哪些关键字呢?
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 220.135.86.153
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1545752503.A.36A.html
※ 编辑: ofspring (220.135.86.153), 12/25/2018 23:43:18
1F:→ Luluemiko: 因为element被移动了,可是index并没有跟着动 12/26 00:00
2F:→ Luluemiko: 直观作法就在回圈前面加一个list的copy(),修改它就好 12/26 00:08
3F:推 germun: 如果元素不重覆用set就好, 除非你只是想试试not in 12/26 00:39
4F:推 iphone2003: 1. not in没用错,2.remove也没错,问题是出在你正在 12/26 03:34
5F:→ iphone2003: 迭代的list_A会在回圈中被改变,这个应该要尽量避免 12/26 03:34
6F:→ iphone2003: 不过推楼上,用set应该最方便 12/26 03:34
7F:推 yangs0618: 请问用set是什麽意思 要达到楼主要的功能怎麽用 12/26 07:33
8F:→ toy9986619: 集合(set) 12/26 08:59
9F:推 Yshuan: List known issue 很多语言都有这问题 12/26 09:07
10F:推 yangs0618: 我知道set XD 是不知道怎麽在这个例子上用 12/26 10:47
11F:推 XperiaZ6C: 在list_A.remove(element)之後把list A跟B都print出来 12/26 11:46
12F:→ XperiaZ6C: 就知道问题在哪了 12/26 11:46
13F:→ ofspring: 感谢各位高手的回覆 我用一个新的list就OK了 12/26 18:03
14F:→ ofspring: set的解法感觉更优雅了 ~ thanks a lot 12/26 18:04
15F:推 iphone2003: 补个set的作法,取交集就好 12/27 01:55
16F:→ iphone2003: set(list_A) & set(list_B) 12/27 01:55