请问这个运行结果是对的吗_
请问这个运行结果是对的吗_
请问这个运行结果是对的吗_
L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
S = set([1, 3, 5, 7, 9, 11])
for l in L:
for s in S.copy():
if l==s:
S.remove(l)
else:
S.add(l)
print(S)
___________________________________________________
set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
不对,嵌套for循环,走外面的for循环取L值,里面的for循环取S值,值会重复,例如外面取1,里面取3,1==3,就会执行add方法,没有实现你想要的。只要遍历一遍就可以,判断从L中取得值与S中的值一不一样就可以了
L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
S = set([1, 3, 5, 7, 9, 11])
print(S)
for x in L:
if(x in S):
S.remove(x)
else:
S.add(x)
print(S)
其实还可以这样写
L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
S = set([1, 3, 5, 7, 9, 11])
s=list(S)
for a in L:
num=0
for b in s:
if a==b:
num+=1
if num>=1:
S.remove(a)
else:
S.add(a)
print(S)
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
s = set([1, 3, 5, 7, 9, 11])
for ss in l:
if ss not in s:
s.add(ss)
print s