习惯c语系的的程序员刚接触python的for/while...else语法时,通常会感觉怪异,下面我用代码给诸位普及下这个知识点:
def intersection(*args):
res = []
for x in args[0]:
for seq in args[1:]:
if x not in seq:break
else:
if x not in res:
res.append(x)
return res
def intersection2(*args):
res = []
for x in args[0]:
common = True
for seq in args[1:]:
if x not in seq:
common = False
if common and x not in res:
res.append(x)
return res
print(intersection('caochao', 'caoyong', 'caoyuju', 'zhouqinyuan'))
print(intersection2('caochao', 'caoyong', 'caoyuju', 'zhouqinyuan'))
两者结果都是:['a', 'o']
查看python语法我们得知:在python中,for/while循环没有被break打断退出时,else语句会执行(原话是else statement will run if didn't exit loop with break)。
for/while...else语句通常用于判断循环里的每一个子因素都要满足某个条件,有一个不满足则使用break语句打断本次循环,否则执行else语句。与在c语系循环中设置标识变量相比(在本例中是common),语法更简洁明了。