在Python中将第一个项目追加到可迭代对象的末尾

huangapple go评论58阅读模式
英文:

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])

huangapple
  • 本文由 发表于 2023年8月8日 21:39:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定