I want no add all the numbers in my string
info="10-20,30,40-50,60,70-80"
print(sum([int(a) for a in info.split(",")[::2].split("-")])+sum([int(b) for b in info.split(",")[1::2]]))
I want no add all the numbers in my string
info="10-20,30,40-50,60,70-80"
print(sum([int(a) for a in info.split(",")[::2].split("-")])+sum([int(b) for b in info.split(",")[1::2]]))
I am not a Python person, so there is definitely a better way to do this, but here is a step-by-step way to get to your desired result. Hopefully, the comments are explanatory. I also commented out several print()
statements that you can re-add if you want to see what transformations happen at each step:
x="10-20,30,40-50,60,70-80"
# Do a first split
xList = x.split(',')
#print(xList)
# Get the non-ranges into their own list
listOfSingles = []
xListSingleNumsOnly = list(filter(lambda x: '-' not in x, xList))
for a in xListSingleNumsOnly:
listOfSingles.append(int(a))
# Get the sum of the non-ranges
listOfSinglesSum = sum(listOfSingles)
#print(listOfSinglesSum)
# Get the ranges into their own list
xListRangesOnly = list(filter(lambda x: '-' in x, xList))
#print(xListRangesOnly)
# Turn the ranges that are currently strings into ints and populate them
# Start with an empty list to hold results of transformations
listOfRanges = []
# Split on the dash
for i in xListRangesOnly:
iSplit = i.split('-')
# For each (pseudo-)range, populate it
listedInts = []
for x in iSplit:
listedInts.append(int(x))
ranged = list(range(listedInts[0],listedInts[1]+1))
# Add up these ranges
rangeSum = sum(ranged)
listOfRanges.append(rangeSum)
# Sum the ranges you just populated
listOfRangesSum = sum(listOfRanges)
#print(listOfRangesSum)
final = listOfSinglesSum + listOfRangesSum
print(final)
Import regular expression library and using findall method, set a search pattern in order to get integers from string.
import re
sum([int(i) for i in re.findall(pattern="\d[,]?[-]?\d",string=info)])