Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

python - 尝试在python中使用for循环输出数学方程式(Trying to outputting a math equation with for loop in python)

So I have changeable sized list with integers in it like [2,5,6,9,1] and I am trying to create an addition formula with for loop:

(所以我有一个可变大小的列表,其中包含整数,例如[2,5,6,9,1],并且我试图用for循环创建一个加法公式:)

z= 1
while z > 0:
    for i in range(len(list)):
        print(list[i],"+", end=" ")
    z = 0
    print("=",sum(list),end=" ")

This is what i am trying and output is:

(这是我正在尝试的输出是:)

2 + 5 + 6 + 9 + 1 + = 23

What should I do if I want to output n integers and n-1 plus signs between integers?

(如果要输出n个整数和n-1加整数之间的符号,该怎么办?)

  ask by user19281 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may use str.join that accept an iterable of strings.

(您可以使用接受字符串迭代的str.join 。)

You need to map each int to str then join them using the + and print the result

(您需要将每个int映射到str然后使用+将它们加入并打印结果)

values = [2, 5, 6, 9, 1]
formula = " + ".join(map(str, values))
print(formula, "=", sum(values))  # 2 + 5 + 6 + 9 + 1 = 23

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...