如何将字符串的所有排列作为字符串列表(而不是元组列表)?

问题描述 投票:4回答:3

目标是创建一个单词中某些字母的所有可能组合的列表...这很好,除了它现在最终作为具有太多引号和逗号的元组列表。

import itertools

mainword = input(str("Enter a word: "))
n_word = int((len(mainword)))

outp = (list(itertools.permutations(mainword,n_word)))

我想要的是:

[yes, yse, eys, esy, sye, sey]

我得到了什么:

[('y', 'e', 's'), ('y', 's', 'e'), ('e', 'y', 's'), ('e', 's', 'y'), ('s', 'y', 'e'), ('s', 'e', 'y')]

在我看来,我只需要删除所有括号,引号和逗号。

我试过了:

def remove(old_list, val):
  new_list = []
  for items in old_list:
    if items!=val:
        new_list.append(items)
  return new_list
  print(new_list)

我只是运行了几次这个功能。但它不起作用。

python python-3.x list tuples itertools
3个回答
2
投票

您可以使用join功能。下面的代码非常完美。我还附上了输出的截图。

import itertools

mainword = input(str("Enter a word: "))
n_word = int((len(mainword)))

outp = (list(itertools.permutations(mainword,n_word)))

for i in range(0,6):
  outp[i]=''.join(outp[i])

print(outp)

enter image description here


7
投票

你可以用这样的理解重新组合这些元组:

Code:

new_list = [''.join(d) for d in old_list]

Test Code:

data = [
    ('y', 'e', 's'), ('y', 's', 'e'), ('e', 'y', 's'),
    ('e', 's', 'y'), ('s', 'y', 'e'), ('s', 'e', 'y')
]

data_new = [''.join(d) for d in data]
print(data_new)

Results:

['yes', 'yse', 'eys', 'esy', 'sye', 'sey']

4
投票

您需要在字符串元组上调用str.join()才能将其转换回单个字符串。您的代码可以通过列表理解简化为:

>>> from itertools import permutations
>>> word = 'yes'

>>> [''.join(w) for w in permutations(word)]
['yes', 'yse', 'eys', 'esy', 'sye', 'sey']

或者您也可以使用map()获得所需的结果:

>>> list(map(''.join, permutations(word)))
['yes', 'yse', 'eys', 'esy', 'sye', 'sey']
© www.soinside.com 2019 - 2024. All rights reserved.