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

标签 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_str = ['c1', 'c3', 'c2', 'c4']

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

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

供您引用。有一个帖子是关于 How to generate permutation matrix based on two lists of str

最佳答案

您可以使用numpy.take:

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

关于python - 如何更改列表中元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53101905/

相关文章:

python - 使用 panda 将列拆分为 csv

java - Flink Python 自定义连接器/源代码

python - python中的while循环,输入和字符串有问题

python - subprocess.Popen 进程标准输出返回空?

python - 更改视频python opencv的设置时出错

python + celery : ignore task results on a per-invocation basis?

python - Elasticsearch查询:范围限制的语法给出400

java - 在运行时更改字符串

python - 从 pandas 的字符串中删除多余的标点符号

python - pytest配置问题(从nosetests(71秒)到pytest(153​​6秒)的过渡)