Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何更改列表中的元素位置_Python_String_Python 3.x_List - Fatal编程技术网

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

Python 如何更改列表中的元素位置,python,string,python-3.x,list,Python,String,Python 3.x,List,我有一个置换矩阵,它是一个平方矩阵,元素不是1就是0 p = [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]] 如果我将p乘以int的列表,列表中元素的位置将会改变。比如说 a_num = [1, 3, 2, 4] np.dot(np.array(p), np.array(a_num).reshape(4,1)) # results is [1, 2, 3, 4] 现在我想更改str的列表: a_s

我有一个置换矩阵,它是一个平方矩阵,元素不是1就是0

p = [[1, 0, 0, 0],
     [0, 0, 1, 0],
     [0, 1, 0, 0],
     [0, 0, 0, 1]]
如果我将
p
乘以
int
的列表,列表中元素的位置将会改变。比如说

a_num = [1, 3, 2, 4]
np.dot(np.array(p), np.array(a_num).reshape(4,1))
# results is [1, 2, 3, 4]
现在我想更改
str
的列表:

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

你知道如何用矩阵
p
实现它吗?请注意,我的实际应用程序可以在列表中包含数十个元素

供您参考。有一篇关于

您可以使用
numpy.take

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

通过在列表中利用enumerate,您可以在不使用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)
输出:

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

它获取
p
的每个内部列表,并在该内部列表的
idx
处使用
a_str
元素,创建一个新的列表

它们都是
'c1..n'
格式吗?
 ['c1', 'c2', 'c3', 'c4']