首页 > 解决方案 > 如何将排列应用于列表?

问题描述

如何让 Sympy Permutation 作用于列表?例如,

from sympy.combinatorics import Permutation

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
perm = Permutation([[0, 2, 8, 6], [1, 5, 7, 3]])
# Then something like...
perm * lst   # This doesn't work. Throws AttributeError because of list

我想要这样的东西返回(在这个例子中):

['g', 'd', 'a', 'h', 'e', 'b', 'i', 'f', 'c']

我已阅读https://docs.sympy.org/latest/modules/combinatorics/permutations.html,但不知道如何。

关于如何解决这个问题的任何建议?

标签: pythonpython-3.xlistpermutationsympy

解决方案


你可以做perm(lst)

>>> from sympy.combinatorics import Permutation
>>> lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> perm = Permutation([[0, 2, 8, 6], [1, 5, 7, 3]])
>>> perm(lst)
['c', 'f', 'i', 'b', 'e', 'h', 'a', 'd', 'g']

您的示例输出似乎具有将给定排列的反向应用于列表的结果 - 如果这是您需要的输出,您需要反转最终列表或排列中的每个列表。

这里

排列可以“应用于”任何类似列表的对象,而不仅仅是排列。


推荐阅读