繁体   English   中英

我将如何用字符串替换 15。 我想用字符串“go”替换可被 15 整除的列表中的任何数字?

[英]How would I replace 15 with a string. I am trying to replace any number in a list that is divisble by 15 with the string "go"?

def b_function(low, high):
    g = []
    for i in range(low,high):
        if i % 3 ==0 or i % 7 ==0 or i % 15 ==0:
            #print(str(g) +" ",end = " ")
            g.insert(len(g),i)
            #i.replace("15","boo")
        #if i % 15 ==0:
            #g.append("Boo")
            print(g)
if __name__ == "__main__":
    num_1 = int(input("Please input the lower limit:\n"))
    num_2 = int(input("Please input the upper limit:\n"))
    c = b_function(num_1,num_2)

我让用户输入范围,以及如何用字符串“go”替换所有可被 15 整除的数字。

修改列表的一种简单方法是使用创建另一个列表的推导式:

>>> numbers = [5, 10, 15, 20, 25, 30, 35, 40, 45]
>>> [n if n % 15 else "go" for n in numbers]
[5, 10, 'go', 20, 25, 'go', 35, 40, 'go']

你运行过你的代码吗? 它会引发错误并且可能不会像您预期的那样工作。

# there are more conditions than number divisible by 15, 
# the if statement execute for the first condition that is True,
# in this case, all number divisible by 3
if i % 3 ==0 or i % 7 ==0 or i % 15 ==0:

# so you will have a list of numbers divisible by 3, even if it is a list of numbers
# divisible by 15, and you successfully replace, you only get a list full of "go"
# as there are no other numbers inserted under if statement
g.insert(len(g),i)

# raise AttributeError here because integer input doesn't have replace function, 
# even it works, you only replace 15 not 30 or 45 etc. and the word will be "boo"
i.replace("15","boo")

# your print function is in the for-loop, so if there are 6 numbers divisible by 15,
# the list will be printed 6 times, is that what you want?
print(g)

还请注意 range(a,b) 中,b 是不包括的,例如 range(0,100) 的数字从 0 到 99,不包括 100。

也许你想要这样的东西?

def b_function(low, high):
    g = []
    # high+1 to include the num_2
    for i in range(low,high+1):
        # directly append "go" to the list when the number is divisible by 15
        # so no need to replace
        if i % 15 == 0:
            g.append("go")
        # regular print out for numbers divisible by 3 or 7
        elif i % 3 == 0 or i % 7 ==0:
            g.append(i)
    # only print the list once after the for-loop
    print(g)

if __name__ == "__main__":
    num_1 = int(input("Please input the lower limit:\n"))
    num_2 = int(input("Please input the upper limit:\n"))
    c = b_function(num_1,num_2)

输出将是:

[3, 6, 7, 9, 12, 14, 'go', 18, 21, 24, 27, 28, 'go']

暂无
暂无

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

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