【问题标题】:Python3: TypeError: sequence item 0: expected str instance, list foundPython3:TypeError:序列项0:预期的str实例,找到列表
【发布时间】:2021-05-06 06:36:37
【问题描述】:

我正在尝试打印单词“otaku”的所有可能的字符替换。

#!/usr/bin/python3

import itertools

user_input = "otaku"

dict = {
'c': ['c', 'C'],
'a': ['a', 'A', '@'],
't': ['t', 'T'],
'k': ['k', 'K'],
'u': ['u', 'U'],
'e': ['e', 'E', '3'],
'o': ['o', 'O', '0']
}

output = ""

for i in itertools.product(dict['o'],dict['t'],dict['a'],dict['k'],dict['u']):
    output += ''.join(i) + "\n"

print(output)

上述脚本有效,但我需要 itertools.product() 输入 (dict['o'],dict['t'],dict['a'],dict['k'],dict['u']) 是动态的(例如,new_list):

#!/usr/bin/python3

import itertools

user_input = "otaku"

dict = {
'c': ['c', 'C'],
'a': ['a', 'A', '@'],
't': ['t', 'T'],
'k': ['k', 'K'],
'u': ['u', 'U'],
'e': ['e', 'E', '3'],
'o': ['o', 'O', '0']
}

new_list = []

for i in user_input:
    new_list.append(dict[i])

output = ""

for i in itertools.product(new_list):
    output += ''.join(i) + "\n"

print(output)

此错误:

TypeError: sequence item 0: expected str instance, list found

我尝试了找到 here 的解决方案,但将列表转换为 str 会破坏 itertools.product 行。

如何将动态输入传递给itertools.product()

期望的输出:

otaku
otakU
otaKu
otaKU
otAku
otAkU
otAKu
otAKU
ot@ku
ot@kU
ot@Ku
ot@KU
oTaku
oTakU
oTaKu
oTaKU
oTAku
oTAkU
oTAKu
oTAKU
oT@ku
oT@kU
oT@Ku
oT@KU
Otaku
OtakU
OtaKu
OtaKU
Ot@KU

【问题讨论】:

    标签: python-3.x list loops dictionary iterator


    【解决方案1】:

    试试for i in itertools.product(*new_list):

    你需要添加一个*来解压new_list

    【讨论】:

    • 哇,我不敢相信这是解决方案。为什么那里需要通配符?
    • 您的代码很好,但是当您将new_list 作为参数传递时,您实际上是在传递一个列表。您要传递的是列表的所有元素。当您添加 * 时,您将解压缩列表并将每个元素作为参数传递。这是预期的结果。
    • 看看这个函数:def test_func(a, b, c): # do something。如果我通过像test_func(new_list) 这样的列表,则表示test_func(a = new_list)。如果我像test_func(*new_list) 这样解压列表,则意味着test_func(a=new_list[0], b = new_list[1]....)
    • 看看这个。如果你知道 args 和 kwargs 是如何工作的,这真的很有用:realpython.com/python-kwargs-and-args
    【解决方案2】:

    你可以使用*来解压:

    for i in itertools.product(*new_list)
    

    您也可以通过列表理解

    来做到这一点
    c = ["".join(x) for x in itertools.product(*new_list)]
    for i in c:
       print(i)
    
    

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 2022-10-18
      • 2017-06-05
      • 1970-01-01
      相关资源
      最近更新 更多