检测列表中的数字组?

时间:2017-02-09 22:03:02

标签: python list grouping

我正在寻找一种方法来对列表中的数字进行分组,同时如果它们属于某个范围则会循环遍历它们。

例如这里是一个数字列表:

days = [18, 19, 26, 9, 15, 16, 22, 2, 9, 15, 16, 23, 28, 30, 6, 13, 19, 20, 25,27,
        4, 11, 17, 18, 25, 1, 8, 14, 15, 22, 27, 29, 6, 13, 19, 20, 26, 27,
        3, 10, 16, 17, 24, 25, 31, 7, 14, 20, 21, 26, 28, 5, 12, 18, 19, 26,
        2, 9, 15, 16, 23, 27, 30, 7, 14, 20, 21, 28]

循环遍历列表时,如果数字大于1且小于32,例如[(18, 19, 26), (9, 15, 16, 22)]等,我想将它们分组为元组列表。有没有人有合理的方法来做到这一点?

我尝试过使用itertools库中的配方但失败了。

示例:

for k, g in groupby(enumerate(days), lambda (i,x):x in date_range):
    print map(itemgetter(1), g)

此示例将生成连续数字列表。我感谢任何帮助。

1 个答案:

答案 0 :(得分:-1)

last_day = 0
sublist = []
result = []
for day in days:
    if day > last_day:
        sublist.append(day)
    else:
        result.append(tuple(sublist))
        sublist = [day]
    last_day = day
result.append(tuple(sublist))  # append the final list

浏览它们并构建子列表,然后将其转换为元组并添加到结果列表中。

结果是:

[(18, 19, 26), (9, 15, 16, 22), (2, 9, 15, 16, 23, 28, 30), 
 (6, 13, 19, 20, 25, 27), (4, 11, 17, 18, 25), (1, 8, 14, 15, 22, 27, 29), 
 (6, 13, 19, 20, 26, 27), (3, 10, 16, 17, 24, 25, 31), 
 (7, 14, 20, 21, 26, 28), (5, 12, 18, 19, 26), 
 (2, 9, 15, 16, 23, 27, 30), (7, 14, 20, 21, 28)]