英文:
Append first item to end of iterable in Python
问题
我需要将一个(通用的)可迭代对象的第一个元素追加为该可迭代对象的最后一个元素(从而“闭合循环”)。我想到了以下方法:
from collections.abc import Iterable
from itertools import chain
def close_loop(iterable: Iterable) -> Iterable:
iterator = iter(iterable)
first = next(iterator)
return chain([first], iterator, [first])
# Examples:
list(close_loop(range(5))) # [0, 1, 2, 3, 4, 0]
''.join(close_loop('abc')) # 'abca'
这个方法可以工作,但似乎有点“笨拙”。我想知道是否有更直接的方法,可以利用itertools
的魔力。如果有使用more_itertools
的解决方案,也非常欢迎。
英文:
I need to append the first item of a (general) iterable as the final item of that iterable (thus "closing the loop"). I've come up with the following:
from collections.abc import Iterable
from itertools import chain
def close_loop(iterable: Iterable) -> Iterable:
iterator = iter(iterable)
first = next(iterator)
return chain([first], iterator, [first])
# Examples:
list(close_loop(range(5))) # [0, 1, 2, 3, 4, 0]
''.join(close_loop('abc')) # 'abca'
Which works, but seems a bit "clumsy". I was wondering if there's a more straightforward approach using the magic of itertools
. Solutions using more_itertools
are also highly welcome.
答案1
得分: 6
这是一个不使用itertools
的版本:
def close_loop(iterable):
iterator = iter(iterable)
first = next(iterator)
yield first
yield from iterator
yield first
英文:
Here is a version which doesn't use itertools
def close_loop(iterable):
iterator = iter(iterable)
first = next(iterator)
yield first
yield from iterator
yield first
答案2
得分: 1
使用itertools.tee
:
from itertools import chain, tee
def close_loop(iterable):
orig, dupl = tee(iterable, 2)
first = next(orig)
return chain(dupl, [first])
使用itertools.tee
函数:
from itertools import chain, tee
def close_loop(iterable):
orig, dupl = tee(iterable, 2)
first = next(orig)
return chain(dupl, [first])
英文:
Using itertools.tee
:
from itertools import chain, tee
def close_loop(iterable):
orig, dupl = tee(iterable, 2)
first = next(orig)
return chain(dupl,[first])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论