如何使用python按升序对数字列表进行分组?

时间:2017-08-17 14:56:05

标签: python

假设我有这个数字列表:

1,2,3,4,7,8,10,12,15,16,17,18,19,20,21,22,24,26,27,29 < / p>

我想根据列表中的升序创建5个偶数组:

第1组: 1,2,3,4,7

第2组: 8,10,12,15,16

第3组: 17,18,19,20,21

等...

我可以使用python执行此操作吗?我知道我可以按0:4分组; 5:9 ......但是我有很多不同长度的列表,我需要将它们分成5个精确的组。

3 个答案:

答案 0 :(得分:4)

你可以试试这个:

l = [1, 2, 3, 4, 7, 8, 10, 12, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 27, 29]

new_groups = [l[i:i+5] for i in range(0, len(l), 5)]

输出:

[[1, 2, 3, 4, 7], [8, 10, 12, 15, 16], [17, 18, 19, 20, 21], [22, 24, 26, 27, 29]]

如果要按编号访问每个组,可以构建字典:

accessing = {i+1:a for i, a in zip(range(5), new_groups)}

print(acessing[2])

输出:

[8, 10, 12, 15, 16]

答案 1 :(得分:2)

对列表进行排序,然后使用itertools中的grouper食谱:

from itertools import zip_longest
l = [1, 2, 3, 4, 7, 8, 10, 12, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 27, 29]
l.sort()

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

groups = list(grouper(l, 5))
print(groups)
# [(1, 2, 3, 4, 7), (8, 10, 12, 15, 16), (17, 18, 19, 20, 21), (22, 24, 26, 27, 29)]

答案 2 :(得分:0)

你可以根据列表的长度来做到这一点。

function edittext_KeyPressFcn(hObject, eventdata, handles)

    key = get(gcf,'CurrentKey');
    if(strcmp(key,'return'))
        commands=get(handles.edittext,'String');
        lastline = commands(end,:) %gets the last written line for execution
    end
end


%put this in where you want the user to click a button and display the text on listofdata textview
set(handles.listofdata,'String',commands); 

然后用剩余的元素完成最后一组:

l = [...]
groupLength = len(l) // 5
groups = [l[i*groupLength:(i+1)*groupLength] for i in range(5)]

或者只是将其余元素放入一个新组:

groups[-1].extend(l[-len(l)%5:])