python关于for循环的几个函数
2个回答
展开全部
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):
for i,e in enumerate(['21dw', 55, 22, 'rw']):
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)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询