【问题标题】:Sorting of lists in number ranges对数字范围内的列表进行排序
【发布时间】:2019-01-01 11:12:58
【问题描述】:
list = [1,2,,3,4,5,6,1,2,56,78,45,90,34]
range = ["0-25","25-50","50-75","75-100"]

我正在用 python 编码。我想对数字范围内的整数列表进行排序并将它们存储在不同的列表中。我该怎么做?

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

【问题讨论】:

  • listrange 作为变量名影子内置插件 - 不要将它们用作变量的名称

标签: python-3.x list sorting


【解决方案1】:

创建一个字典,其中每个 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 exclusive 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]]

【讨论】:

  • 谢谢。它帮助很大。
【解决方案2】:

另一种针对您的特殊情况(定期间隔的 bin)的稳定 bin 方法是使用计算的键 - 这将消除每个步骤中的键搜索。

稳定搜索意味着列表中的数字顺序与输入数据中的顺序相同:

def inRegularIntervals(data, interval):
    """Sorts elements of data into bins of regular sizes.
    The size of each bin is given by 'interval'."""
    # init dict so keys are ordered - collection.defaultdict(list) 
    # would be faster - but this works for lists of a couple of
    # thousand numbers if you have a quarter up to one second ...

    # if random key order is ok, shorten this to d = {}    
    d = {k:[] for k in range(0, max(data), interval)}  
    for n in data:
        key = n // interval # get key
        key *= interval
        d.setdefault(key, [])
        d[key ].append(n) # add number
    return d

用于随机数据:

from random import choices

data = choices(range(100), k = 50)
data.append(135) # add a bigger value to see the gapped keys

binned = inRegularIntervals(data, 25)
print(binned)

输出(\n 和空格添加):

{ 0: [19, 9, 1, 0, 15, 22, 4, 9, 12, 7, 12, 9, 16, 2, 7], 
 25: [25, 31, 37, 45, 30, 48, 44, 44, 31, 39, 27, 36], 
 50: [50, 50, 58, 60, 70, 69, 53, 53, 67, 59, 52, 64], 
 75: [86, 93, 78, 93, 99, 98, 95, 75, 88, 82, 79], 
100: [], 
125: [135], }

要对分箱列表进行就地排序,请使用

for k in binned:
    binned[k].sort()

得到:

{ 0: [0, 1, 2, 4, 7, 7, 9, 9, 9, 12, 12, 15, 16, 19, 22], 
 25: [25, 27, 30, 31, 31, 36, 37, 39, 44, 44, 45, 48], 
 50: [50, 50, 52, 53, 53, 58, 59, 60, 64, 67, 69, 70], 
 75: [75, 78, 79, 82, 86, 88, 93, 93, 95, 98, 99], 
100: [], 
125: [135]}

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 2020-06-12
    • 2020-03-21
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2015-06-03
    相关资源
    最近更新 更多