python科普(1)-for/while...else

习惯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),语法更简洁明了。

转载于:https://my.oschina.net/tudas/blog/174761

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值