# coding:utf-8
# python中的循环
# 1,for 循环;for in iterable
# iterable可以是列表,元组,字典,字符串
# books = ["红楼梦","三国演义","水浒传","西游记"]
# books = ("红楼梦","三国演义","水浒传","西游记")
# books = "红楼梦"
# books = {"红楼梦","三国演义","水浒传","西游记"}
books = {"a":"红楼梦","b":"三国演义","c":"水浒传","d":"西游记"}
for book in books:
print(books[book])
# 2, 利用字典内置函数items进行for循环
for key,value in books.items():
print(key,value)
# 3, python内置函数range
# range(start,end,step=1) start开始的数字,类似索引的左边,end结束的数字,类似索引的右边,step跳步
for item in range(1,10,1):
print(item)
# 4,for循环中删除元素
test_list = [3, 6, 8, 9, 25, 36, 100, 105,4,6,8,12]
# test_list[::-1] 返回倒序的列表
for i in test_list[::-1]:
if i %2 ==0:
test_list.remove(i)
print(test_list)
# 列表推导式
# 列表推导式也叫做列表解析式,是一种快速创建列表的简洁语法。
# 列表推导式以[]中括号为标志,一般由表达式、循环语句、条件语句组成(条件语句非必须)
# 列表推导式,20以内所有偶数的平方
print([x ** 2 for x in range(20) if x % 2 == 0])
# 运行结果:[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
# 常见的推导式方法
# 元组推导式如下:
# 元组推导式
t_1 = (x for x in range(10)) # 结果是生成器对象,使用tuple()函数将其转换为元组
print(tuple(t_1))
# 运行结果:(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
# 字典推导式如下:
# 字典推导式
print({x:x**2 for x in range(10)})
# 运行结果:{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
# 集合推导式如下:
# 集合推导式
print({x for x in range(10)})
# 运行结果:{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
# 循环实现九九乘法表
for i in range(1, 10):
for j in range(1, i+1):
print("{}*{}={}".format(j,i,i*j),end=' ')
print('')
# 各种推导式,感觉 =看起来不明了,代码是简单,
|