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

时间:2018-04-24 21:05:17

标签: python python-3.x

我需要帮助编辑我的代码,以便输出结束如下:

  

输入目标字词:红色

     

输入替换字:粉色

     

替换人数: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()

请帮助,非常感谢

1 个答案:

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

这样的事情应该有效。你不必在替换函数中粘在一起的单词,你可以建立新的列表。