【问题标题】:Get all possible strings if the letters are a lists如果字母是列表,则获取所有可能的字符串
【发布时间】:2023-01-20 02:23:41
【问题描述】:

**我想要达到的目标: ** 我正在尝试制作一个 python 脚本来生成所有可能的字母列表字符串

这些列表按顺序包含组成字符串的所有可能字母,例如:

`firstLetter = ["a", "s"]
secondLetter = ["e", "r"]
thirdLetter = ["w", "s"]`

如果这是一个愚蠢的问题,我很抱歉,我是 python 的新手

我试过这个:

`import itertools

firstLetter = ["a", "s"]
secondLetter = ["e", "r"]
thirdLetter = ["w", "s"]

comfirst = list(itertools.combinations(range(firstLetter), 1))
combsecond = list(itertools.combinations(range(secondLetter), 1))
combthird = list(itertools.combinations(range(thirdLetter), 1))



comb = list(itertools.combinations(range(combfirst,combsecond,combthird), 3))

print(comb) `

预期结果:

* 哇哦 arw 缝 srw aes 阿尔斯 ses srs *

**实际结果: ** *TypeError: 'list' 对象不能解释为整数 *

【问题讨论】:

  • 你期待range(firstLetter)做什么?你不是指firstLetter吗?
  • TypeError 应该指向问题所在,描述也正是它所说的。你希望range(["a", "s"])做什么?

标签: python python-3.x list python-itertools


【解决方案1】:

你可以使用itertools.product

from itertools import product
list(map("".join, product(firstLetter, secondLetter, thirdLetter)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2018-04-22
    • 2017-10-23
    • 2021-12-31
    • 2020-03-24
    相关资源
    最近更新 更多