简体   繁体   English

打印列表中所有字符串的排列

[英]print permutations of all strings in a list

I am trying to print the permutations of all the members in a list,but my script is printing the permutations of only last member of list ie 'DMNCT'. 我正在尝试打印列表中所有成员的排列,但是我的脚本仅打印列表中最后一个成员的排列,即“ DMNCT”。

from itertools import permutations
element_all=['EESE', 'TTDT', 'SAIFE', 'DMNCT']
i=0
for i in range (len(element_all)):
    perms = [''.join(p) for p in permutations(element_all[i])]
print perms

It seems that my for loop is not working correctly.I am fairly new to python.Any help would be appreciated. 似乎我的for循环无法正常工作。我是python的新手,将不胜感激。

This is happening because you're replacing perms each loop. 发生这种情况是因为您要替换每个循环的perms You should define the list outside the loop and then extend it inside the loop. 您应该在循环外定义列表,然后在循环内extend它。

from itertools import permutations
element_all=['EESE', 'TTDT', 'SAIFE', 'DMNCT']
perms = []
for i in element_all:
    perms.extend([''.join(p) for p in permutations(i)])
print perms

Or define the list all at once in a comprehension 或一次定义所有列表

perms = [''.join(p) for i in element_all for p in permutations(i)]

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

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