'How to add multiple numbers in one list (python) [closed]
Say if I want to add 11 to all the numbers in the variable "e". How would I do it?
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"
So it should now say (after you add 11 and print it)
32,56,53,82
code:
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)```
Solution 1:[1]
try this:
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)
Solution 2:[2]
First, you split the terms, then convert them into an integer, add them, then convert them back to string, and print them.
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]))
This is the main part of the code:
','.join([str(int(answer)+int(add)) for answer in ans])
a join operator needs a a list of string with another string to join them.
Here, [str(int(answer)+int(add)) for answer in ans] means convert the answer and add to an integer, add them, and convert them back to a string. Then, the .join() joins the list with the string provided. Since , is provided, the output will be 32,56,53,82
Solution 3:[3]
You can use this for string input => string output:
e = "21,45,42,71"
','.join([str(int(x)+11) for x in e.split(',')])
# Out[29]: '32,56,53,82'
Input list of integers => list of integers:
e = [21, 45, 42, 71]
[x+11 for x in e]
# Out[33]: [32, 56, 53, 82]
Input list of integers => list of integers (with library)
e = [21, 45, 42, 71]
import numpy as np
np.add(e, 11).tolist()
Solution 4:[4]
try some list comprehension
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)
out
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]
Solution 5:[5]
If you need the result as a single string:
output = ",".join(str(int(add) + int(x)) for x in ans.split(","))
print(output)
If you're ok with the result being a list of numbers:
putput = [int(add) + int(x) for x in ans.split(",")]
print(output)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kaartik Nayak |
| Solution 2 | |
| Solution 3 | Andreas |
| Solution 4 | It_is_Chris |
| Solution 5 |
