使用 Python 中的不等式将数组分成三个新数组

Seperate array into three new arrays using inequalities in Python

我正在尝试使用不等式将一个数组拆分为三个新数组。

这会让您了解我正在努力实现的目标:

measurement = [1, 5, 10, 13, 40, 43, 60]

for x in measurement:
    if 0 < x < 6:
        small = measurement
    elif 6 < x < 15:
        medium = measurement
    else
        large = measurement

预期输出:

small = [1, 5]
medium = [10, 13]
large = [40, 43, 60]

使用 bisect module 您可以按照以下方式做一些事情:

from bisect import bisect
breaks=[0,6,15,float('inf')]
buckets={}

m = [1, 5, 10, 13, 40, 43, 60]

for e in m:
    buckets.setdefault(breaks[bisect(breaks, e)], []).append(e)

然后您将得到一个与您要查找的内容相匹配的列表字典:

>>> buckets
{6: [1, 5], 15: [10, 13], inf: [40, 43, 60]}

您还可以将断点和列表形成元组,这些元组将成为形成子列表的字典:

m = [1, 5, 10, 13, 40, 43, 60]
buckets=[('small',[]), ('medium',[]), ('large',[]), ('other',[])]

breaks=[(0,6),(6,15),(15,float('inf'))]

for x in m:
    buckets[
        next((i for i,t in enumerate(breaks) if t[0]<=x<t[1]), -1)
           ][1].append(x)

>>> dict(buckets)
{'small': [1, 5], 'medium': [10, 13], 'large': [40, 43, 60], 'other': []}

你可以使用 numpy:

arr = np.array(measurement)     
small = arr[(arr>0)&(arr<6)]    # array([1, 5])
medium = arr[(arr>6)&(arr<15)]  # array([10, 13])
large = arr[(arr>15)]           # array([40, 43, 60])

您还可以使用字典:

d = {'small':[], 'medium':[], 'large':[]}
for x in measurement:
    if 0 < x < 6:
        d['small'].append(x)
    elif 6 < x < 15:
        d['medium'].append(x)
    else:
        d['large'].append(x)

输出:

{'small': [1, 5], 'medium': [10, 13], 'large': [40, 43, 60]}

如果您的数组已排序,您可以这样做:

measurement = [1, 5, 10, 13, 40, 43, 60]
one_third = len(measurement) // 3
two_third = (2 * len(measurement)) // 3

small = measurement[:one_third]
medium = measurement[one_third : two_thirds]
large = measurement[two_thirds:]

您可以很容易地概括为带有循环的任意数量的拆分。不确定您是否明确想要这些不等式或只是将数组分成三部分。如果是第一个,我的回答不对