在Python中,字符串列表可以通过连接在一起
','.join(['ab', 'c', 'def'])
Run Code Online (Sandbox Code Playgroud)
但是我怎么能轻易加入一个数字列表或其他一些东西呢?像这样:
0.join([1, 2, 3]) ---> [1, 0, 2, 0, 3]
Run Code Online (Sandbox Code Playgroud)
现在我必须这样做:
sum([[x, 0] for x in [1, 2, 3]], [])[:-1]
Run Code Online (Sandbox Code Playgroud)
你可以做一个:
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]))
Run Code Online (Sandbox Code Playgroud)