python_列表推导式

列表推导式的练习

# 练习1:使用列表推导式生成1--50之间能被3或者5整除的数字
# list01 = []
# for item in range(1, 51):
#     if item % 3 == 0 or item % 5 == 0:
#         list01.append(item)
# print(list01)
list01 = [item for item in range(1, 51) if item % 3 == 0 or item % 5 == 0]
print(list01)
# 练习2:使用列表推导式生成5--60之间数字的平方
# list02 = []
# for item in range(5, 61):
#     list02.append(item ** 2)
# print(list02)
list02 = [item ** 2 for item in range(5, 61)]
print(list02)
# 练习3:将1970年到2050年之间的闰年存入列表
# list03 = []
# # for year in range(1970, 2051):
# #     if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
# #         list03.append(year)
list03 = [years for years in range(1970, 2051) if years % 4 == 0 and years % 100 != 0 or years % 400 == 0]
print(list03)
发布了39 篇原创文章 · 获赞 0 · 访问量 515

猜你喜欢

转载自blog.csdn.net/weixin_46198526/article/details/104099085