如何更改列表中的项目分组?

时间:2017-06-04 16:43:18

标签: python list grouping

所以如果我有这样的清单:

x = [0,1,2,3,4,5,6,7,8,9]

如何将此列表转换为以下内容:

x = [01,23,45,67,89]

我该怎么做?

我知道内置的zip函数, 但我不想要tuple,我想要将2个数字分组为1。

3 个答案:

答案 0 :(得分:3)

你可以试试这个:

x = [0,1,2,3,4,5,6,7,8,9]

x = map(str, x)

new_list = map(int, [x[i]+x[i+1] for i in range(0, len(x)-1, 2)])

答案 1 :(得分:2)

使用zip和列表推导,假设数据类型从int列表到字符串列表:

In [1]: x = [0,1,2,3,4,5,6,7,8,9]

In [2]: pairs = zip(x[::2], x[1::2])

In [3]: pairs
Out[3]: [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

In [4]: [str(fst) + str(snd) for fst, snd in pairs] 
Out[4]: ['01', '23', '45', '67', '89']

答案 2 :(得分:1)

这更容易理解,并且是一个单线:

 # l = list of string of items in list u with index(i) and index(i+1) and i increments by 2
 l = [ str( u[i]) + str( u[i+1]) for i in range( 0, len(u), 2)]