Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert numeric string ranges to a list in Python

Tags:

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.

like image 463
jncraton Avatar asked Jun 19 '11 21:06

jncraton


People also ask

How do you convert a list of objects to a list of strings 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.

How do you convert a list of strings to a list of numbers?

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.

Can we convert a number into list in Python?

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.


2 Answers

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] 
like image 176
FogleBird Avatar answered Oct 06 '22 01:10

FogleBird


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!

like image 25
JBernardo Avatar answered Oct 06 '22 02:10

JBernardo