如何实现两个有相似元素列表,其中一个删除相似元素——python
#Before the starting
This is my first blog, cause i want to learn english, so i will try to finish every blog all by english. i hope my english will turn to be great!!!
#the following is the main body
here have two lists,
str1 = [1,2,3,4]
str2 = [3,4,5,6]
i want to find the elements that is in str1 but not in str2, at the first, i try the following code:
// An highlighted block
for i in str1:
if i in str2:
str1.remove(i)
print(str1)
I hope the result was ‘[1,2]’,however the result is ‘[1,2,3]’. this confused me, and i take so much time to figure out where the problem is.
when we use ‘for’ cycle to traverse every element, we can’t change(add/delete) the list.
here is the right code:
//copy a list of str1
// a blank list
str1_copy =[]
for i in str1:
str1_copy.append(i)
for i in str1_copy:
if i in str2:
str1.remove(i)
print(str1)
the result is what i expect exactly:
‘[1,2]’