比较常见的,顺序遍历字符串中的每一个字符:
>>> s="abc"
>>> for each in s:
... print(each)
...
a
b
c
或者遍历一个列表中的每一个元素:
>>> l=[1,2,3]
>>> for each in l:
... print(each)
...
1
2
3
问题1 遍历一个字符串,同时得到每一个元素的索引:
>>> s="abc"
>>> for idx,val in enumerate(s):
... print(idx,val)
...
0 a
1 b
2 c
问题2 遍历所有可能的组合
>>> import itertools
>>> s="abc"
>>> r=itertools.combinations(s,2)
>>> for each in r:
... print(each)
...
('a', 'b')
('a', 'c')
('b', 'c')
https://medium.com/@jasonrigden/a-guide-to-python-itertools-82e5a306cdf8
网友评论