简体   繁体   English

如何更改列表中的元素位置

[英]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. 我有一个置换矩阵,它是一个方阵,元素是1或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. 如果我将p乘以int列表,则列表中元素的位置将被更改。 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 : 现在我要更改str的列表:

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

to

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

Do you know how to achieve it with matrix p ? 你知道如何用矩阵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 有一篇关于如何根据两个str列表生成置换矩阵的帖子

You can use numpy.take : 你可以使用numpy.take

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

You can do it without numpy by leveraging enumerate in a list comprehension: 你可以通过在列表理解中利用枚举来实现它而不是numpy:

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. 它接受p每个内部列表,并在该内部列表的idx处使用a_str的元素作为a_str ,由此创建一个新列表。

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

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