如何在一个列表中添加多个数字 (python)

How to add multiple numbers in one list (python)

假设我想将 11 添加到变量“e”中的所有数字。我该怎么做?

ans = input("Enter here string of numbers here") 
add = input("How much do you want to add each individual numbers by: ")  #here is when it will minus each individual number print(output)

e = "21,45,42,71"

所以它现在应该说(在你添加 11 并打印它之后)

32,56,53,82

代码:

ans = input("Enter string of numbers here")
add = input("How much do you want to add each individual numbers by: ")

#here is when it will minus each individual number
print(output)```

试试这个:

a= "21,45,42,71" #your string
lst = list(map(int,a.split(","))) #splitted every number and converted to int and stored in list
result = list(map(lambda x:x+11,lst)) #added 11 to each number
print(result) 

如果您需要单个字符串形式的结果:

output = ",".join(str(int(add) + int(x)) for x in ans.split(","))
print(output)

如果您认为结果是一个数字列表:

putput = [int(add) + int(x) for x in ans.split(",")]
print(output)

您可以将其用于字符串输入 => 字符串输出:

e = "21,45,42,71"

','.join([str(int(x)+11) for x in e.split(',')])
# Out[29]: '32,56,53,82'

输入整数列表 => 整数列表:

e = [21, 45, 42, 71]

[x+11 for x in e]
# Out[33]: [32, 56, 53, 82]

输入整数列表 => 整数列表(带库)

e = [21, 45, 42, 71]

import numpy as np
np.add(e, 11).tolist()

尝试一些列表理解

ans = input("Enter here string of numbers here: ") 
add = input("How much do you want to add each individual numbers by: ")

nums = [int(x)+int(add) for x in ans.split(',')]
print(nums)

出来

Enter here string of numbers here:  23,24,25,26
How much do you want to add each individual numbers by:  11
[34, 35, 36, 37]

首先,您拆分项,然后将它们转换为整数,将它们相加,然后将它们转换回字符串,并打印它们。

ans = input("Enter here string of numbers here: ").split(",") 
add = input("How much do you want to add each individual numbers by: ")
print("Here is the sum: ",','.join([str(int(answer)+int(add)) for answer in ans]))

这是代码的主要部分:

','.join([str(int(answer)+int(add)) for answer in ans])

a join 运算符需要一个 string 列表和另一个字符串来连接它们。

这里,[str(int(answer)+int(add)) for answer in ans]表示将answeradd转换为整数,相加,再转换回字符串。然后,.join() 使用提供的字符串加入列表。由于提供了 ,,因此输出将为 32,56,53,82