我需要帮助编辑我的代码,以便输出结束如下:
输入目标字词:红色
输入替换字:粉色
替换人数:3
原始列表:
blue, red, yellow, green, red, black, white, gray, blue, blue, red
替换清单:
blue, pink, yellow, green, pink, black, white, gray, blue, blue, pink
基本上,我需要修复我的代码,以便我的原始列表和替换列表使用for循环,但我还必须使用replace函数,同时我必须打印替换的数量(其中我不知道怎么办。) 这是我的代码到目前为止的样子:
def replace (list1, target, replaceWord):
new = ""
for word in list1:
if word == target:
new += replaceWord + (", "[-1])
else:
new += word + (", "[-1])
return new
def main():
print ("Welcome! Enter your words one at a time and hit enter after each value.\nWhen you are done entering values, type stop.")
inp = input ("Enter first value: ")
list1 = []
while inp !="stop":
list1.append(inp)
inp = input ("Enter first value: ")
target = input ("Enter target word :")
replaceWord = input ("Enter replacement word: ")
print()
newlist = replace(list1,target,replaceWord)
for i in newlist:
## reps = ( )
## reps += str (replaceWord)
print ("Number of replacements: " +(reps))
print ("Original list: " + (str (list1)))
print ("List with replacement: " + newlist)
main()
请帮助,非常感谢
答案 0 :(得分:4)
def replace (list1, target, replaceWord):
new = []
replacements_no = 0
for word in list1:
if word == target:
new.append(replaceWord)
replacements_no += 1
else:
new.append(word)
return new, replacements_no
def main():
print ("Welcome! Enter your words one at a time and hit enter after each value.\nWhen you are done entering values, type stop.")
inp = input ("Enter first value: ")
list1 = []
while inp !="stop":
list1.append(inp)
inp = input ("Enter first value: ")
target = input("Enter targe word :")
replaceWord = input("Enter replacement word: ")
print()
newlist, replacements = replace(list1,target,replaceWord)
print("Number of replacements: {}".format(replacements))
print ("Original list: " + (str (list1)))
print ("List with replacement: {}".format(', '.join(newlist)))
main()
这样的事情应该有效。你不必在替换函数中粘在一起的单词,你可以建立新的列表。