Python 循环技巧记录

1. enumerate

Input:

for i, j in enumerate(range(2,5)):
    print(i,j)

Output:

0 2
1 3
2 4

注:i 为 index,j 为 value

2. zip

Input:

for i, j in zip(range(2,5), range(3,6)):
    print(i,j)

Output:

2 3
3 4
4 5

注:zip中短的一项决定循环次数

3. itertools.product

Input:

from itertools import product

for i, j in product(range(2), range(3)):
    print(i,j)

Output:

0 0
0 1
0 2
1 0
1 1
1 2

4. tqdm.tqdm

Input:

from tqdm import tqdm

for i in tqdm(range(10), desc='test'):
    10**1000000
    continue

Output:

test: 100%|████████████████████████████████████████████████████████████████████████████| 10/10 [00:02<00:00,  4.91it/s]

猜你喜欢

转载自blog.csdn.net/weixin_43605641/article/details/114633559