字符串的遍历:
for str in "abcdefghijklmnopqrstuvwxyz":
print(str,end="")
# >>>abcdefghijklmnopqrstuvwxyz
列表的遍历及推导式:
1. 列表的遍历:
①:
for data in [1,2,3,4,5,6,7]:
print(data,end="")
# >>>1234567
②:
list = [1,2,3,4,5,6,7,8,9,10]
for i in range(len(list)):
print(list[i],end="")
# >>>12345678910
2. 列表的推导式:
推导式又称解析式。
[转]基本格式:
variable = [out_exp_res for out_exp in input_list if out_exp == 2]
- out_exp_res:列表生成元素表达式,可以是有返回值的函数。
- for out_exp in input_list:迭代input_list将out_exp传入out_exp_res表达式中。
- if out_exp == 2:根据条件过滤哪些值可以。
实例:
list = [ i for i in range(1,50) if i % 3 == 0]
print(list)
# >>>[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]
元组的遍历:
- 元组的遍历:
①
tup = (1,2,3,4,5,6,7,8,9,0)
for i in tup:
print(i,end="")
# >>>1234567890
②
tup = (1,2,3,4,5,6,7,8,9,0)
i = 0
while i < len(tup):
print(tup[i],end="")
i += 1
# >>>1234567890
字典的遍历和推导式:
1. 字典的推导式:
[转]基本格式:
{ key_expr: value_expr for value in collection if condition }
实例:
用字符串和其长度创建字典:
names = ['zhangsan','lisi','wangwu','zhaoliu','liuqi']
dic = {key:val for val,key in enumerate(names)}
print(dic)
# >>>{'zhangsan': 0, 'lisi': 1, 'wangwu': 2, 'zhaoliu': 3, 'liuqi': 4}
2. 字典的遍历:
names = {'zhangsan': 0, 'lisi': 1, 'wangwu': 2, 'zhaoliu': 3, 'liuqi': 4}
for key,val in names.items():
print(key,val," ",end="")
# >>>zhangsan 0 lisi 1 wangwu 2 zhaoliu 3 liuqi 4
集合的遍历和推导式:
1.集合的推导式:
基本格式:
set = { expr for value in collection if condition }
实例:
set = {x for x in [1,2,3]}
print(set)
# >>>{1, 2, 3}
2.集合的遍历:
set = {1, 2, 3}
for x in set:
print(x,' ',end="")
# >>>1 2 3