我有一个列表
A = [“贷款”,“梅塞德斯”,“布加迪”,“ a4”,“王牌”,“美国”,“选举”, “总统”,“星系”,“ 7s”,“佳能”,“ macbook”,“ beiber”, '蜘蛛人','奇迹','钢铁侠']
和
B = ['贷款','网络','华盛顿','王牌','佳能','伦敦']
当我为了从B
获取不存在的单词而做了一些事情时
列出A
:
for i in A:
for j in B:
if j not in i:
print (j)
它给出循环的周期为:-
network
washington
trump
canon
london
loans
network
washington
trump
canon
london
loans
network
washington
trump
canon
london
loans
network
washington
trump
canon
london
.......
.......
.......
为什么呢?我要返回的所有内容
network
washington
london
答案 0 :(得分:3)
for i in B:
if i not in A:
print (i)
答案 1 :(得分:2)
使用not in
方法:
not_in_list = [b for b in B if b not in A]
for n in not_in_list:
print(n)
为更清楚起见,如果原始代码编写如下,则可以使用它:
for b in B:
unique = True
for a in A:
if b == a:
unique = False
break
if unique == True:
print(b)
答案 2 :(得分:0)
使用set
差异
print(set(B) - set(A))
答案 3 :(得分:0)
尝试一下
A = ['loans', 'mercedez', 'bugatti', 'a4', 'trump', 'usa', 'election', 'president', 'galaxy', '7s', 'canon', 'macbook', 'beiber', 'spiderman', 'marvels', 'ironmen']
B = ['loans', 'network', 'washington', 'trump', 'canon', 'london']
print('\n'.join([i for i in B if i not in A]))
输出:
network
washington
london