Gah*_*han 1 python for-loop python-3.x
我有字典列表,为简单起见,我把它们写成字符串:
ls = ['element1', 'element2', 'element3', 'element4', 'element5', 'element6', 'element7', 'element8', 'element9', 'element10']
Run Code Online (Sandbox Code Playgroud)
我试图从列表中处理一对元素如下:
#m1. Step for loop by size two with if condition
for x in ls:
if ls.index(x)%2 == 0:
# my code to be process
print(x) # for simplicity I just printed element
#m2. tried another way like below:
for x in range(0, len(ls), 2):
# this way give me output of alternate element from list
print(ls[x])
Run Code Online (Sandbox Code Playgroud)
有没有办法在迭代列表项时m1只获取备用元素m2?
您可以按两个步骤切片列表; 利用记忆:
for x in ls[::2]:
print(x)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1105 次 |
| 最近记录: |