简体   繁体   中英

Splitting a list

I've scoured various resources and can't figure out how to do a rather simple operation.

Right now, I have a list as follows:

li = [['a=b'],['c=d']]

I want to transform this into:

li = [['a','b'],['c','d']]

As I understand it, split("=") only applies to string types. Is there an equivalent method for lists?

Pardon the simplicity of my question...

-Dan

You want this:

[x[0].split('=') for x in li]
# prints [['a', 'b'], ['c', 'd']]

To grab a question from a comment further down the post, the reason split works for x[0] is that x represents the inner list. That's accomplished by the for x in li . Also, I fixed mine to read for x in li and not for x in test as I had assigned your examples to a variable called 'test' on my system.

You can use map() :

>>> li = [['a=b'],['c=d']]
>>> map(lambda x: x[0].split('='), li)
[['a', 'b'], ['c', 'd']]

This traverses the list li and applies the lambda function to every element. As every element of the list is again a list with one element, x[0] takes this element, which is a string, splits it and returns a new list with both values.

Warning - its been a while since I did any python, but your issue is more general.

You are correct in that split applies to strings.

What you need to do is split the VALUE contained in your list not the list itself.

So you would do something like

newValue = split('=', li[0][0]) 
li[0] = newValue

Is this what you are looking for ? map(lambda y:y.split('='),map(lambda x:x[0], li))

Presuming each sublist consists of individual strings of the form a=b :

>>> [el[i].split('=') for el in li for i in range(len(el))]
[['a', 'b'], ['c', 'd']]

(Indeed, what you're splitting is the inner string a=b . So the split() string method works fine.)

EDIT : A much more elegant way of doing this double list comprehension is:

>>> [a.split('=') for el in li for a in el]
[['a', 'b'], ['c', 'd']]

There have been a number of good suggestions made, so the OP should be able to learn a good amount of Python for it. Important to remember is that what is being split is li[i][j], ie an item of the list that is an item of the list li.

您可以这样做:

[k[0].split("=") for k in li]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM