I would like to be able to convert a string such as "1,2,5-7,10" to a python list such as [1,2,5,6,7,10]. I looked around and found this, but I was wondering if there is a clean and simple way to do this in Python.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings] . It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function.
Method #2: Using map() map function can be used to perform the following task converting each of the string converted numbers to the desired integer value to be reconverted to the list format.
def f(x): result = [] for part in x.split(','): if '-' in part: a, b = part.split('-') a, b = int(a), int(b) result.extend(range(a, b + 1)) else: a = int(part) result.append(a) return result >>> f('1,2,5-7,10') [1, 2, 5, 6, 7, 10]
I was able to make a true comprehension on that question:
>>> def f(s): return sum(((list(range(*[int(j) + k for k,j in enumerate(i.split('-'))])) if '-' in i else [int(i)]) for i in s.split(',')), []) >>> f('1,2,5-7,10') [1, 2, 5, 6, 7, 10] >>> f('1,3-7,10,11-15') [1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15]
the other answer that pretended to have a comprehension was just a for loop because the final list was discarded. :)
For python 2 you can even remove the call to list
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With