如何将不同的列表减少到完全相同的长度?

How to reduce different lists to the exactly same length?

我有一些长度不同的非常大的列表。我想将它们全部减少到完全相同的大小(例如减少到 1000 个元素)!我知道有一些“相似”的问题,但我没有找到我的问题的正确答案。所以这里是我所做的一个例子。为了简单起见,我们在这里只使用三个列表。

a = list(range(10000))
b = list(range(9879))
c = list(range(10345))

# Now I want to reduce all the lists to exactly 1000 elements
# I tried this approched like I read in some other questions:
aa = a[::len(a) // 1000] # len(aa) = 1000
bb = b[::len(b) // 1000] # len(bb) = 1098
cc = c[::len(c) // 1000] # len(cc) = 1035

但是使用这种方法,结果列表的长度不同。我现在如何随机删除 list bb 和 list cc 的一些元素,使其也具有 1000 个元素的精确长度?我不想只删除最后一个 x 元素或第一个 x 元素。 或者是否有更好的解决方案来将不同长度的列表减少到完全相同的长度?

编辑:结果列表(aa、bb、cc)的顺序应与我的原始列表相同。我不想随机洗牌。

您可以使用 random.shuffle 函数,这样您就可以获取数组的前 x 个元素。

import random
a = list(range(10000))
b = list(range(9879))
c = list(range(10345))

random.shuffle(a)
random.shuffle(b)
random.shuffle(c)

# Now I want to reduce all the lists to exactly 1000 elements
# I tried this approched like I read in some other questions:
aa = a[:1000] 
bb = b[:1000] 
cc = c[:1000] 

我会像你那样做,然后剪掉最后一个元素..当数字不能除以时,如果没有一些额外的元素,就不可能均匀地分布元素 1000 所以:

aa = a[::len(a) // 1000] [:1000]
bb = b[::len(b) // 1000][:1000]
cc = c[::len(c) // 1000] [:1000]

如果你坚持不取出剩下的最后一个元素..你可以在上面的代码之后使用另一个答案并随机选择..

根据第一条评论,您的代码如下所示:

from random import sample

a = list(range(10000))
b = list(range(9879))
c = list(range(10345))

# Now I want to reduce all the lists to exactly 1000 elements
# I tried this approched like I read in some other questions:
aa = sample(a[::len(a) // 1000],1000) # len(aa) = 1000
bb = sample(b[::len(b) // 1000],1000) # len(bb) = 1000
cc = sample(c[::len(c) // 1000],1000) # len(cc) = 1000

注意 aa 的元素现在被打乱了

一个非洗牌的解决方案是:

import numpy as np

a = np.array(range(10000))
b = np.array(range(9879))
c = np.array(range(10345))

# Now I want to reduce all the lists to exactly 1000 elements
# I tried this approched like I read in some other questions:
indeces = np.array(range(len(a))) ## make indeces
remove = np.random.permutation(len(a))[:1000] ## select indeces to remove
selected = np.in1d(indeces, remove, assume_unique=True) ## make list of indeces that are selected, faster on unique 
aa = a[selected] # len(aa) = 1000 ## select indeces

indeces = np.array(range(len(b)))
remove = np.random.permutation(len(b))[:1000]
selected = np.in1d(indeces, remove)
bb = b[selected] # len(bb) = 1000

indeces = np.array(range(len(c)))
remove = np.random.permutation(len(c))[:1000]
selected = np.in1d(indeces, remove)
cc = c[selected]  # len(cc) = 1000
import random
a = list(range(10000))
b = list(range(9879))
c = list(range(10345))


def randomm(x):
    while True:
        u = []
        r = random.randint(0,x)
        if r in u:
            pass
        else:
            u.append(r)
            return r

aa = [a[randomm(len(a))] for i in range(1000)]
bb = [b[randomm(len(b))] for i in range(1000)]
cc = [c[randomm(len(c))] for i in range(1000)]

我为随机生成器创建了一个容器,因此该数字会重复。