繁体   English   中英

替换,循环,格式化并计算Python列表中的替换

[英]Replace, for loops, format, and count the replacements in Python list

我需要编辑代码的帮助,因此输出最终如下所示:

输入目标词:红色

输入替换词:粉红色

更换数量: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()

请帮忙,非常感谢

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()

这样的事情应该起作用。 您不必在替换功能中放在一起,可以建立新列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM