如题所述
for ... in ...
// for ... in 字符串for i in 'abc':
print(i)
'''
a
b
c
'''
// for ... in 数组
for i in ['a', 'b', 'c']:
print(i)
'''
a
b
c
'''
// for ... in 元组
for i in ('a', 'b', 'c'):
print(i)
'''
a
b
c
'''
// for ... in 字典(得到的是字典的key)
for k in {'学号':30,'姓名':'小明'}:
print(k)
'''
姓名
学号
'''
// for ... in 字典.items()(得到的是字典的key, value)
for k, v in {'学号':30,'姓名':'小明'}.items():
print(k, v)
'''
姓名 小明
学号 30
'''
for ... in range(...)
// for ... in range(num)for i in range(3):
print(i)
'''
0
1
2
'''
// for ... in range(num1, num2)
for i in range(1, 3):
print(i)
'''
1
2
'''
// for ... in range(num1, num2, num3)
for i in range(3, 1, -1):
print(i)
'''
3
2
'''
for i in range(1, 5, 2):
print(i)
'''
1
3
'''
倒叙
for i in reversed([1,2,3,4]):print(i)
’‘’
4
3
2
1
‘’‘
又想得到遍历次数,又想得到数组值
for i,e in enumerate(array):
print(i, e)
'''
0 21dw
1 55
2 22
3 rw
'''
列表生成式
[...for ... in array]]
print([x * x for x in [2, 34, 324, 43]])'''
[4, 1156, 104976, 1849]
'''
//相当于
list = []
for x in [2, 34, 324, 43]:
list.append(x * x)
print(list)
温馨提示:答案为网友推荐,仅供参考
第1个回答 2018-06-24
range