[英]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个整数之间的加号怎么办?
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
# Using f-strings
formula = f'{" + ".join(map(str, values))} = {sum(values)}'
print(formula)
Use join
:使用join
:
def printfn(alist):
expr = " + ".join((map(str, alist)))
sum_val = sum(alist)
print("{} = {}".format(expr, sum_val))
a = [1,2,3]
printfn(a)
# 1 + 2 + 3 = 6
b = [1,2,3,4]
printfn(b)
# 1 + 2 + 3 + 4 = 10
If my understanding is correct you looking for something recognize the list changing... 如果我的理解是正确的,那么您正在寻找可以识别列表变化的东西。
This will print out the new sum if an item was added to you list. 如果将一项添加到您的列表,这将打印出新的总和。
Here i created an example: 在这里,我创建了一个示例:
import threading
import time
import random
LIST = []
def add_function():
_old_len = 0
while True:
if len(LIST) >= 2 and len(LIST) > _old_len:
addstring = " + ".join(map(str, LIST))
print(addstring, "=", sum(LIST))
_old_len = len(LIST)
def increase_function():
while True:
LIST.append(random.randint(1, 20))
time.sleep(2)
if __name__ == "__main__":
x = threading.Thread(target=add_function)
y = threading.Thread(target=increase_function)
x.start()
y.start()
y.join()
x.join()
Another possibility is to use sep=
parameter of print()
function.另一种可能性是使用sep=
print()
函数的参数。
For example:例如:
lst = [2,5,6,9,1]
print(*lst, sep=' + ', end=' ')
print('=', sum(lst))
Prints:印刷:
2 + 5 + 6 + 9 + 1 = 23
Make the for loop in range( len(list)-1 ) and add a print (list[len(list)-1]) before z=0在 range( len(list)-1 ) 中创建 for 循环并在 z=0 之前添加一个 print (list[len(list)-1])
list = [2,5,6,9,1]
z= 1
while z > 0:
for i in range( len(list)-1 ):
print(list[i],"+", end=" ")
print (list[len(list)-1],end=" ")
print("=",sum(list),end=" ")
z = 0
You can use enumerate() , starting with an index of 1您可以使用enumerate() ,从索引 1 开始
>>> l= [2,5,6,9,1]
>>> s = ''
>>> sum_ = 0
>>> for i, v in enumerate(l, 1):
if i == len(l):
# If the current item is the length of the list then just append the number at this index, and the final sum
s += str(v) + ' = ' + str(sum_)
else:
# means we are still looping add the number and the plus sign
s += str(v)+' +
>>> print(s)
2 + 5 + 6 + 9 + 1 = 23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.