简体   繁体   English

获取列表中嵌套元素的所有排列 - python 2

[英]Getting all the permutations of a nested elements in a list- python 2

So its not the permutations Im having trouble with, rather that the outcome lists are not equivalent to the original list I started with.所以这不是我遇到问题的排列,而是结果列表不等于我开始的原始列表。 The list is this,名单是这样的,

B=[[m, b], [c, g], [d, f]]

and the code Ive used to get all the permutation is this, along with the outcome,我用来获得所有排列的代码是这个,连同结果,

C=list(itr.permutations(B))
C
 [([m, b], [c, g], [d, f]),
 ([m, b], [d, f], [c, g]),
 ([c, g], [m, b], [d, f]),
 ([c, g], [d, f], [m, b]),
 ([d, f], [m, b], [c, g]),
 ([d, f], [c, g], [m, b])]

Is there any way to not have the inner lists in parentheses, rather instead in square bracket, because as of now C[0] is not the same as B, when in fact they should be equal.有什么办法可以不在括号中,而是在方括号中,因为到目前为止 C[0] 与 B 不同,而实际上它们应该相等。

C[0]==B
False 

Ive defined the letters (m, b, d, etc) as symbols in sympy rather then as strings.我已经将字母(m、b、d 等)定义为 sympy 中的符号,而不是字符串。 Any advice is appreciated.任何建议表示赞赏。

You can use map() to turn the tuples into lists:您可以使用map()将元组转换为列表:

>>> import itertools as itr
>>> B=[[m, b], [c, g], [d, f]]
>>> C = map(list, itr.permutations(B))
>>> C
[[['m', 'b'], ['c', 'g'], ['d', 'f']], [['m', 'b'], ['d', 'f'], ['c', 'g']], [['c', 'g'], ['m', 'b'], ['d', 'f']], [['c', 'g'], ['d', 'f'], ['m', 'b']], [['d', 'f'], ['m', 'b'], ['c', 'g']], [['d', 'f'], ['c', 'g'], ['m', 'b']]]
>>> C[0] == B
True

Also, you can use itertoolsimap() if you want to keep it as an iterator.此外,如果要将其保留为迭代器,可以使用 itertoolsimap()

Just use C[0][0] == B[0]只需使用C[0][0] == B[0]

>>> print(C)
[(['m', 'b'], ['c', 'g'], ['d', 'f']), (['m', 'b'], ['d', 'f'], ['c', 'g']), (['c', 'g'], ['m', 'b'], ['d', 'f']), (['c', 'g'], ['d', 'f'], ['m', 'b']), (['d', 'f'], ['m', 'b'], ['c', 'g']), (['d', 'f'], ['c', 'g'], ['m', 'b'])]
>>> print(B)
[['m', 'b'], ['c', 'g'], ['d', 'f']]
>>> C[0][0]
['m', 'b']
>>> B[0]
['m', 'b']
>>> C[0][0] == B[0]
True
>>> C[0][1] == B[1]
True

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

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