gpt4 book ai didi

python - 一次替换列表中的项目

转载 作者:太空宇宙 更新时间:2023-11-04 05:32:49 25 4
gpt4 key购买 nike

我正在尝试为我正在学习的 Python 类(class)编写“填空”。我才刚刚开始,我遇到了一些我不太明白的事情。

这是主要的代码块:

easy = ['In ','___(1)___',' if you want to pass the W3 validator, make sure you close your ','___(2)___','!']

easy_list = ['HTML','tags']
blank_list = ['___(1)___','___(2)___','___(3)___','___(4)___','___(5)___','___(6)___']

def num_replace(level,word):
new_level = []
for i in level:
if i == blank_list[word]:
new_level[word] = easy_list[word]
else:
new_level.append(i)
return new_level

我试过将函数输出为像这样的简单打印:

print ''.join(num_replace(easy,0))
print ''.join(num_replace(easy,1))

但我会得到的是:

HTML if you want to pass the W3 validator, make sure you close your ___(2)___!

然后……

In tags if you want to pass the W3 validator, make sure you close your !

所以我尝试这样输出它:

happy_list = ''.join(num_replace(easy,0))
print happy_list
happy_list = ''.join(num_replace(easy,1))
print happy_list

但我得到了同样的结果。

澄清我想要得到的是:

在调用 num_replace 之前:在 ___(1)___ 中,如果您想通过 W3 验证程序,请确保关闭您的 ___(2)___!

num_replace(easy,0) 应该输出:在 HTML 中如果你想通过 W3 验证器,确保你关闭你的 ___(2)___!

num_replace(easy,1): 在 HTML 中,如果你想通过 W3 验证器,请确保关闭你的标签!

最佳答案

这里有两个问题:

1 - 您正在将新词附加到第 word 位置。 new_level[word] = append(easy_list[word])2 - 您没有将更改保存到新字符串,因为字符串是不可变的。所以这里是变化:

>>> def num_replace(level, word):
new_level = []
for i in level:
if i == blank_list[word]:
new_level.append(easy_list[word])
else:
new_level.append(i)
return new_level

>>>
>>>
>>> ''.join(num_replace(easy,0))
'In HTML if you want to pass the W3 validator, make sure you close your ___(2)___!'
>>> ''.join(num_replace(easy,1))
'In ___(1)___ if you want to pass the W3 validator, make sure you close your tags!'
>>>

现在,您必须以这种方式保存所做的更改:

>>> l = num_replace(easy,0)
>>> l
['In ', 'HTML', ' if you want to pass the W3 validator, make sure you close your ', '___(2)___', '!']
>>>
>>> ''.join(num_replace(l,1))
'In HTML if you want to pass the W3 validator, make sure you close your tags!'
>>>

或者如果你想在一行中:

>>> ''.join(num_replace(num_replace(easy,0),1))
'In HTML if you want to pass the W3 validator, make sure you close your tags!'

关于python - 一次替换列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36564966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com