我想从列表中添加以下内容,但结果只是 concatinates

i want to add the following from a list but the result only concatinates

n 的样本值为 5

    n = input("Enter a No: ")
    n = "{0}+{0}{0}+{0}{0}{0}".format(n)
    n = n.split("+")
    a=n[0] 
    b=n[1]
    c=n[2] 
    n = (a + b + c) 
    print(n)

预期结果:615

拆分后 n 是一个字符串列表,你应该将它们转换为 int。

n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")
a=int(n[0])
b=int(n[1])
c=int(n[2])
n = (a + b + c) 
print(n)

如有必要,添加 try/except 以正确处理未传递有效数字的情况。

您只需在代码中添加 1 行,它应该是 运行。

您需要将列表中的所有元素转换为 int 才能执行加法。

试试这个:

n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")

n = list(map(int, n))

a=n[0] 
b=n[1]
c=n[2] 
n = (a + b + c) 
print(n)

在这里,你应该怎么做:

n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = list(map(int, n.split("+")))
print(sum(n))

我已使用 map to convert a list of string to a list of int and sum 对列表的所有元素求和。我假设您需要对列表中的所有元素求和。如果只想对前三个元素求和,则:

a=n[0] 
b=n[1]
c=n[2] 
n = (a + b + c) 
print(n)

注意:如果您使用的是最新版本的Python,那么n = map(int, n)将return一个类型错误:'map' object is not subscriptable .您需要将对象 return 由 map 显式转换为列表。

你可以用这个。

n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
out=sum([int(i) for i in n.split('+')])

如果您只想添加前三个元素,请使用此选项。

out_3=sum([int(i) for i in n.split('+')[:4]])