Frage

I have a simple list as below:

lst = ['11 12221/n']

I want to split the first item into a list as below:

['11', '12221']

This seems relatively simple to me but I cant get it to work. My first approach was to do:

lst[0].split() 

but when I print list no changes have occurred. I therefore tried:

newLst=[]

for x in lst:
    newList.append(x.split())

But from this I get

[['11', '12221\n']]

I think I must fundamentally be misunderstanding list comprehension, could someone explain why my code didnt work and how it should be done?

Thank you

War es hilfreich?

Lösung 2

You can do it as:

lst = ['11 12221\n']

lst = lst[0].split()

list[0] gets you '11 12221\n' which you then split() and assign back to lst giving you:

['11', '12221\n']

You have to assign the split back to the variable

Note: You should not name your variables as ony of the python reserved words. Use perhaps lst instead.

If you only want to split at a space, do: split(' ') instead.

Demo: http://repl.it/R8w

Andere Tipps

I believe you are looking for this:

>>> lst = ['11 12221\n']
>>> # Split on spaces explicitly so that the \n is preserved
>>> lst[0].split(" ")
['11', '12221\n']
>>> # Reassign lst to the list returned by lst[0].split(" ")
>>> lst = lst[0].split(" ")
>>> lst
['11', '12221\n']
>>>

Use a list comprehension:

[part for entry in origlist for part in entry.split(None, 1)]

This allows for multiple strings and splits just once (so only two elements are ever created for each string).

You need to assign the result of the call to std.split to something:

>>> my_list = ['11 12221\n']     # do not name a variable after a std lib type
>>> my_list = my_list[0].split()
>>> print my_list
['11', '12221']

The main issue is that the call to str.split returns a list of strings. You were just discarding the result.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top