Python: "1-2-3-4" to [1, 2, 3, 4]

What is the best way to convert a formatted string to a "1-2-3-4"

list [1, 2, 3, 4]

? The string can also be empty, in which case the conversion must return an empty list []

.

This is what I have:

map(lambda x: int(x),
    filter(lambda x: x != '',
           "1-2-3-4".split('-')))

      

EDIT: Sorry to all those who answered, before I fixed my question, it was unclear for the first minute or so.

+2


source to share


7 replies


You can use a list comprehension to make it shorter. Use a if

blank line for accounting.



the_string = '1-2-3-4'

[int(x) for x in the_string.split('-') if x != '']

      

+12


source


>>> for s in ["", "0", "-0-0", "1-2-3-4"]:
...     print(map(int, filter(None, s.split('-'))))
... 
[]
[0]
[0, 0]
[1, 2, 3, 4]

      



+8


source


Converting higher-order functions to a more readable list comprehension

[ int(n) for n in "1-2-3-4".split('-') if n != '' ]

      

The rest is fine.

+4


source


From the format of your example, you want int in a list. If so, you will need to convert strings to int. If not, then you are done after splitting the line.

text="1-2-3-4"

numlist=[int(ith) for ith in text.split('-')]
print numlist
[1, 2, 3, 4]

textlist=text.split('-')
print textlist
['1', '2', '3', '4']

      

EDIT: Revising my answer to reflect the update in the question.

If the list might be garbled then "try ... catch" if your friend. This will ensure that the list is either built or you get an empty list.

>>> def convert(input):
...     try:
...         templist=[int(ith) for ith in input.split('-')]
...     except:
...         templist=[]
...     return templist
...     
>>> convert('1-2-3-4')
[1, 2, 3, 4]
>>> convert('')
[]
>>> convert('----1-2--3--4---')
[]
>>> convert('Explicit is better than implicit.')
[]
>>> convert('1-1 = 0')
[]

      

+2


source


I would go with this:

>>> the_string = '1-2-3-4- -5-   6-'
>>>
>>> [int(x.strip()) for x in the_string.split('-') if len(x)]
[1, 2, 3, 4, 5, 6]

      

+1


source


def convert(s):
    if s:
        return map(int, s.split("-"))
    else:
        return []

      

0


source


you don't need a lambda, and split won't give you empty elements:

map(int, filter(None,x.split("-")))

      

0


source







All Articles