在for循环中处理alternate元素而不使用索引值

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

Mos*_*oye 6

您可以按两个步骤切片列表; 利用记忆:

for x in ls[::2]:
    print(x)
Run Code Online (Sandbox Code Playgroud)

  • @Gahan你用什么计时?你应该使用`timeit`.两次运行不足以实现可靠的计时. (3认同)