繁体   English   中英

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)

尝试一下:(无外部lib的纯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()将其放入矩形martix中, .T切换行和列, .flatten()再次将其放入线性向量中

现在您只需要为.reshape([step, repetition])零件提供参数,例如.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM