所以我有一个可变大小的列表,其中包含整数,例如[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=" ")
这是我正在尝试的输出:
2 + 5 + 6 + 9 + 1 + = 23
如果我要输出n个整数和n-1加整数之间的符号,该怎么办?
答案 0 :(得分:1)
您可以使用str.join
接受可迭代的字符串。您需要将每个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)
答案 1 :(得分:0)
使用G3 = 1574842022157
:
join
答案 2 :(得分:0)
另一种可能性是使用sep=
函数的print()
参数。
例如:
lst = [2,5,6,9,1]
print(*lst, sep=' + ', end=' ')
print('=', sum(lst))
打印:
2 + 5 + 6 + 9 + 1 = 23
答案 3 :(得分:-1)
在range(len(list)-1)中进行for循环,并在z = 0之前添加打印内容(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
答案 4 :(得分:-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