how to loop through list multiple times in Python

匿名 (未验证) 提交于 2019-12-03 09:05:37

问题:

Can you loop through list (using range that has a step in it) over and over again until all the elements in the list are accessed by the loop?

I have the following lists:

result = [] list = ['ba', 'cb', 'dc', 'ed', 'gf', 'jh'] 

i want the outcome (result) to be:

result = ['dc', 'cb', 'ba', 'jh', 'gf', 'ed'] 

How do i make it loop through the first list, and appending each element to result list, starting from the third element and using 5 as a step, until all the elements are in the results list?

回答1:

Assuming the step and the length of the list are coprime, you can do:

result = [] list = ['ba', 'cb', 'dc', 'ed', 'gf', 'jh'] start = 2 step = 5 end = start + step*len(list) for i in range(start, end, step):     result.append(list[i%len(list)]) print result 

Result:

['dc', 'cb', 'ba', 'jh', 'gf', 'ed'] 


回答2:

There is no need to loop through a list multiple times.As a more pythonic way You can use itertools.cycle and islice :

>>> from itertools import cycle,islice >>> li= ['ba', 'cb', 'dc', 'ed', 'gf', 'jh'] >>> sl=islice(cycle(li),2,None,4) >>> [next(sl) for _ in range(len(li))] ['dc', 'ba', 'gf', 'dc', 'ba', 'gf'] 

Note that in your expected output the step is 5 not 4.So if you use 5 as slice step you'll get your expected output :

>>> sl=islice(cycle(li),2,None,5) >>> [next(sl) for _ in range(len(li))] ['dc', 'cb', 'ba', 'jh', 'gf', 'ed'] 


回答3:

A very simple solution was posted earlier, not sure why it was removed:

>>> a = ['ba', 'cb', 'dc', 'ed', 'gf', 'jh'] >>> result = [a[n] for n in range(2, -4, -1)] >>> result ['dc', 'cb', 'ba', 'jh', 'gf', 'ed'] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!