python的for in用法的巧妙用法

import random
ou = "偶数"
ji = "奇数"
a = range(1,11)
x = 0
while x < 10:
list = random.sample(a,10)
print(list)
if list[0] % 2 != 0:
print(ji, end=",")
else:
print(ou, end=",")
if list[1] % 2 != 0:
print(ji, end=",")
else:
print(ou, end=",")
if list[2] % 2 != 0:
print(ji, end=",")
else:
print(ou, end=",")
if list[3] % 2 != 0:
print(ji, end=",")
else:
print(ou, end=",")
if list[4] % 2 != 0:
print(ji, end=",")
else:
print(ou, end=",")
if list[5] % 2 != 0:
print(ji, end=",")
else:
print(ou, end=",")
if list[6] % 2 != 0:
print(ji, end=",")
else:
print(ou, end=",")
if list[7] % 2 != 0:
print(ji, end=",")
else:
print(ou, end=",")
if list[8] % 2 != 0:
print(ji, end=",")
else:
print(ou, end=",")
if list[9] % 2 != 0:
print(ji)
else:
print(ou)
x += 1 #第一段代码
使用for in之后的代码 import random
ou = "偶数"
ji = "奇数"
a = range(1,11)
x = 0
while x < 10:
list = random.sample(a,10)
print(list)
for y in list:
if y %2 == 0:
print(ou,end=",")
else :
print(ji,end=",")
print()#换行,如果不加这个的话就变成一长条了
x +=1
【python的for in用法的巧妙用法】2段代码实现的功能是一样的,但是使用for in循环之后效率提升了很多,代码也简洁了很多

    推荐阅读