连接列表中的多个项目

时间:2015-12-06 16:22:05

标签: python list

我想知道是否有任何可能的方法来连接列表中的多个项目并以pythonic方式返回另一个列表。

E.g

[a,b,c,d,e]

如果我的输出

[ab,cd,e] 

我的代码是这样的:

x = ['a','b','c','d','e']
a = []
for i in range(0,len(x),2):
    if i + 2 >= len(x):
        a.append(x[i])
    else:
        a.append(x[i] + x[i+1])

Output of a:
['ab','cd','e']

有更好的方式或更多的pythonic方式来做到这一点?我正在使用python2.7

2 个答案:

答案 0 :(得分:1)

使用join连接输入列表的切片。

n=2  # or 5, or 10
output = [ ''.join(input[i:i+n]) for i in range(0, len(input), n)]

答案 1 :(得分:1)

Python文档的the documentation部分有一个grouper函数,您可能会发现它很有用:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

以下是我如何使用它:

from itertools import izip_longest
import operator

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

def concat_groups(iterable, n):
    groups = grouper(iterable, n, fillvalue='')
    return [ ''.join(g) for g in groups ]

x = ['a','b','c','d','e']
concat_groups(x, 2) # ==> ['ab', 'cd', 'e']
concat_groups(x, 3) # ==> ['abc', 'de']
相关问题