joh*_*ohn 19 python list cycle
说我有一个清单:
l = [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
我想循环一下.通常,它会做这样的事情,
1, 2, 3, 4, 1, 2, 3, 4, 1, 2...
Run Code Online (Sandbox Code Playgroud)
我希望能够在周期中的某个点开始,不一定是索引,但可能与元素匹配.假设我想从列表中的任何元素开始==4,然后输出将是,
4, 1, 2, 3, 4, 1, 2, 3, 4, 1...
Run Code Online (Sandbox Code Playgroud)
我怎么能做到这一点?
ovg*_*vin 20
看一下itertools模块.它提供了所有必要的功能.
from itertools import cycle, islice, dropwhile
L = [1, 2, 3, 4]
cycled = cycle(L) # cycle thorugh the list 'L'
skipped = dropwhile(lambda x: x != 4, cycled) # drop the values until x==4
sliced = islice(skipped, None, 10) # take the first 10 values
result = list(sliced) # create a list from iterator
print(result)
Run Code Online (Sandbox Code Playgroud)
输出:
[4, 1, 2, 3, 4, 1, 2, 3, 4, 1]
Run Code Online (Sandbox Code Playgroud)
使用算术运算mod符.假设你是从位置开始k,那么k应该像这样更新:
k = (k + 1) % len(l)
Run Code Online (Sandbox Code Playgroud)
如果你想从某个元素而不是索引开始,你可以随时查找k = l.index(x)x就是所需的项目.
当你可以用几行代码自己完成事情时,我不太喜欢导入模块。这是我的没有导入的解决方案:
def cycle(my_list, start_at=None):
start_at = 0 if start_at is None else my_list.index(start_at)
while True:
yield my_list[start_at]
start_at = (start_at + 1) % len(my_list)
Run Code Online (Sandbox Code Playgroud)
这将返回一个循环列表的(无限)迭代器。要获取循环中的下一个元素,您必须使用以下next语句:
>>> it1 = cycle([101,102,103,104])
>>> next(it1), next(it1), next(it1), next(it1), next(it1)
(101, 102, 103, 104, 101) # and so on ...
>>> it1 = cycle([101,102,103,104], start_at=103)
>>> next(it1), next(it1), next(it1), next(it1), next(it1)
(103, 104, 101, 102, 103) # and so on ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14615 次 |
| 最近记录: |