如何根据变量进行自定义列表分组?

时间:2017-06-05 01:51:48

标签: python list grouping list-comprehension

说我有一个生成的列表,如:

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

然后我把它分开:

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

这个列表理解:

list_x = [0,1,2,3,4,5,6,7,8,9]
grp_count = 2
new_list = map(int, [list_x[i+0]+list_x[i+1] for i in range(0, len(list_x)-1, grp_count)])

如何制作此代码,以便将其分组为基于“grp_count”的分组

例如group_count = 5

list_x = [01234,56789]

我知道我必须以某种方式为每次添加分组大小插入多个list_x[i+n]

3 个答案:

答案 0 :(得分:1)

这看起来很像https://docs.python.org/3/library/itertools.html

中的itertools石斑鱼配方
from itertools import zip_longest

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 zip_longest(*args, fillvalue=fillvalue)

然后

list_x = [0,1,2,3,4,5,6,7,8,9]
print(list(grouper(list_x, 5, 0)))

给出

[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]

答案 1 :(得分:1)

正如我在评论中所说,没有办法在Python中创建一个显示类似[01234,56789]的整数列表,因为Python没有显示带有前导零的整数值像那样。最接近的是[1234, 56789]

但是,你可以创建一个字符串列表,其中包含这些数字:

def grouper(n, iterable):
    return zip(*[iter(iterable)]*n)

list_x = [0,1,2,3,4,5,6,7,8,9]
grp_count = 5
new_list = [''.join(map(str, g)) for g in grouper(grp_count, list_x)]
print(new_list)  #-> ['01234', '56789']

答案 2 :(得分:0)

您可以使用list comprehension来执行此示例:

def grouper(a, num):
    if num > int(len(a)/2):
        return []
    # If you need to return only a list of lists use:
    # return [a[k:k+num] for k in range(0, len(a), num)]
    return ["".join(map(str, a[k:k+num])) for k in range(0, len(a), num)]

a = [0,1,2,3,4,5,6,7,8,9]
print(grouper(a, 2))
print(grouper(a, 5))

输出:

['01', '23', '45', '67', '89']
['01234', '56789']