Reputation: 1029
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
Upvotes: 1
Views: 301
Reputation: 7519
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.
Upvotes: 0
Reputation: 47968
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.
Upvotes: 9
Reputation: 1903
Is this what you are looking for ?
map(lambda y:y.split('='),map(lambda x:x[0], li))
Upvotes: 0
Reputation: 816232
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.
Upvotes: 3
Reputation: 8757
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
Upvotes: 0