Python 如何打乱有序列表以生成元素序列?

Python how to shuffle an ordered list to make sequences of elements?

例如我们有一个有序列表:

a = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

我想重新排列这个数组以形成:

a = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

目前我在做:

a = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])
n_unique_elements = 4
arrays_with_same_elements = np.array_split(a, 5)

for idx in range(n_unique_elements):
    final_list.append(list_similar_a[0][idx])
    final_list.append(list_similar_a[1][idx])
    final_list.append(list_similar_a[2][idx])
    final_list.append(list_similar_a[3][idx])
    final_list.append(list_similar_a[4][idx])

所以变量

final_list = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4] 

必须有一种 pythonic 方法可以做到这一点。也许是 numpy 中的内置函数?您想到了哪些其他不同的技术来解决这个问题?

您可以在 sort() 方法中使用 key 参数: https://docs.python.org/3.3/howto/sorting.html#key-functions 要么 使用 set()

a = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
b = set(a)
final_list = list(b) * len(b)

尝试一下:(纯 python 没有外部库)

STEP = 3
lst0 = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
lst1 = []

for x in range(0, STEP):
    for y in range(0, len(lst0), STEP):
        lst1.append(lst0[y + x])
print(lst1)

输出

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

因此,您可以使用 numpy:

a.reshape([4,3]).T.flatten()

所以 .reshape() 将其放入矩形矩阵中,.T 切换行和列,.flatten() 再次将其放入线性向量中

现在您只需要为重塑部分提供参数,例如.reshape([step, repetition])

如果每个元素的频率相同且事先已知,此解决方案也可行

FREQ = 3
output = a[::FREQ] * (len(a) // FREQ)

另一个基于numpy的解决方案是这样的:

FREQ = 3
output = a.reshape((-1, FREQ)).flatten(order='F')

order='F' 参数按列展平矩阵。

试试这个:

    a = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])
    uniqueValues, occurCount = np.unique(a, return_counts=True) # uniqueValues is the array of unique elements of main list
                                                                #occurCount is array containing frequency of unique elements
    common_occur=min(occurCount)                                # get frequency of co-occurrance

    final_array=np.tile(uniqueValues,common_occur)              #get tiled output array