在数字范围内对列表进行排序

时间:2018-07-24 18:21:47

标签: python-3.x list sorting

list = [1,2,,3,4,5,6,1,2,56,78,45,90,34]
range = ["0-25","25-50","50-75","75-100"]

我正在用python编码。我想对整数列表进行排序,然后将它们存储在不同的列表中。我该怎么办?

我在范围列表中指定了我的范围。

1 个答案:

答案 0 :(得分:0)

创建一个字典,将每个 bin 的最大值作为键。遍历您的数字并将其附加到每个 bin-key

的值的列表中
l = [1,2,3,4,5,6,1,2,56,78,45,90,34]

# your range covers 25 a piece - and share start/endvalues.
# I presume [0-25[ ranges

def inRanges(data,maxValues):
    """Sorts elements of data into bins that have a max-value. Max-values are
    given by the list maxValues which holds the explusive upper bound of the bins."""
    d = {k:[] for k in maxValues} # init all keys to empty lists
    for n in data:
        key = min(x for x in maxValues if x>n) # get key
        d[key].append(n) # add number
    return d


sortEm =  inRanges(l,[25,50,75,100])

print(sortEm)

print([ x for x in sortEm.values()])

输出:

 {25: [1, 2, 3, 4, 5, 6, 1, 2],  50: [25, 45, 34], 
  75: [56],                     100: [78, 90]}

 [[1, 2, 3, 4, 5, 6, 1, 2], [25, 45, 34], [56], [78, 90]]