Python中是否有类似于“连接”的通用列表函数?

5 投票
5 回答
730 浏览
提问于 2025-04-18 00:51

在Python中,可以通过以下方式把一串字符串连接在一起:

','.join(['ab', 'c', 'def'])

但是如果我想简单地把一串数字或者其他东西连接在一起呢?比如这样:

0.join([1, 2, 3])  --->  [1, 0, 2, 0, 3]

现在我必须这样做:

sum([[x, 0] for x in [1, 2, 3]], [])[:-1]

5 个回答

0

对于较新的Python版本,下面的代码应该可以正常工作。

def join(joiner, iterable):
    """Small helper that does similar things as "foo".join("bar") """
    it = iter(iterable)
    head, tail = next(it, None), it
    if head is not None:
        yield head

    for item in tail:
        yield joiner
        yield item


assert list(join("a", range(4))) == [0, "a", 1, "a", 2, "a", 3]
assert list(join("a", [])) == []
assert list(join("a", [0])) == [0]

我是不是漏掉了什么特殊情况?

0

大家都在告诉你,join是一个字符串的方法,而不是列表的方法。

不过你总是可以这样做:

[int(x) for x in '0'.join(map(str, [1, 2, 3]))]
0

你现在的方法不太对。你可以写一个循环来计算总和,或者你可以写一个循环,在遍历列表的过程中把每个项目加起来。否则,你就无法进行你想要的调整。

2

只是因为大家都喜欢那些难以理解的一行代码:

import itertools

def join(sep, col):
    return itertools.islice(itertools.chain.from_iterable(itertools.izip(itertools.repeat(sep), col)), 1, None)

附言:最好参考一下 RemcoGerlich的回答。那样更容易看懂。

5

你可以自己做一个:

def join_generator(joiner, iterable):
    i = iter(iterable)
    yield next(i)  # First value, or StopIteration

    while True:
       # Once next() raises StopIteration, that will stop this
       # generator too.
       next_value = next(i)
       yield joiner
       yield next_value

joined = list(join_generator(0, [1, 2, 3, 4]))

撰写回答