aura
aura

Reputation: 543

How to change elements positions in a list

I have a permutation matrix, which is a square matrix and the elements are either 1 or 0.

p = [[1, 0, 0, 0],
     [0, 0, 1, 0],
     [0, 1, 0, 0],
     [0, 0, 0, 1]]

If I multiply p to a list of int, the positions of elements in the list will be changed. For example

a_num = [1, 3, 2, 4]
np.dot(np.array(p), np.array(a_num).reshape(4,1))
# results is [1, 2, 3, 4]

Now I want to changes a list of str:

a_str = ['c1', 'c3', 'c2', 'c4']

to

['c1', 'c2', 'c3', 'c4']

Do you know how to achieve it with matrix p? Please note that my real application can have tens of elements in the list.

For your information. There is a post about How to generate permutation matrix based on two lists of str

Upvotes: 1

Views: 111

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51643

You can do it without numpy by leveraging enumerate in a list comprehension:

p = [[1, 0, 0, 0],
     [0, 0, 1, 0],
     [0, 1, 0, 0],
     [0, 0, 0, 1]]

a_str = ['c1', 'c3', 'c2', 'c4']

b_str = [a_str[idx] for row in p for idx,i in enumerate(row) if i == 1]

print(b_str)

Output:

 ['c1', 'c2', 'c3', 'c4']

It takes each inner list of p and uses the element of a_str at the idx of that inner list that is one, creating a new list by that.

Upvotes: 1

Francisco
Francisco

Reputation: 11476

You can use numpy.take:

>>> numpy.take(numpy.array(a_str), numpy.array(a_num)-1)
array(['c1', 'c2', 'c3', 'c4'], dtype='|S2')

Upvotes: 2

Related Questions