简体   繁体   中英

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

For instance we have an ordered list:

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

I want to reshuffle this array to form:

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

Currently I'm doing:

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])

So the variable

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

There must a pythonic way of doing this. Perhaps a built-in function in numpy ? What other different techniques come to your mind to solve this problem?

You can use the key parameter in sort() method: https://docs.python.org/3.3/howto/sorting.html#key-functions or using set()

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

Try it: (pure python without external lib)

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)

output

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

So, You can use numpy:

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

so the .reshape() puts it into a rectangualr martix, the .T switches rows and columns and the .flatten() puts it in a linear vector again

now you only need to come up with parameters for the reshape part eg .reshape([step, repetition])

If the frequency of each element is the same and is known beforehand, this solution would also work

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

Another numpy -based solution is this:

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

The order='F' argument flattens the matrix by columns.

Try this:

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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