split string into list of tuples?
Question:
I have a string of key-value pairs, which unfortunately are separated by the same symbol. Is there a way to “just split” it into a list of tuples, without using a lambda?
Here is what i have:
Moscow|city|London|city|Royston Vasey|vilage
What i want:
[("Moscow","city"), ("London", "city")....]
Answers:
This is a pretty easy one really…
first, split the string on '|'
then zip
every other element together:
data = s.split('|')
print zip(data[::2],data[1::2])
In python3, you’ll need: print(list(zip(data[::2],data[1::2]))
def group(lst, n):
for i in range(0, len(lst), n):
val = lst[i:i+n]
if len(val) == n:
yield tuple(val)
a = 'Moscow|city|London|city|Royston Vasey|vilage'
list(group(a.split('|'), 2))
The output is [('Moscow', 'city'), ('London', 'city'), ('Royston Vasey', 'vilage')]
s = 'Moscow|city|London|city|Royston Vasey|vilage'
it = iter(s.split('|'))
print [(x,next(it)) for x in it]
Python3:
>>> s = "Moscow|city|London|city|Royston Vasey|vilage"
>>> list(zip(*[iter(s.split('|'))]*2))
[('Moscow', 'city'), ('London', 'city'), ('Royston Vasey', 'vilage')]
Python2:
zip(*[iter(s.split('|'))]*2)
You could use city, status, remaining = s.split("|", 2)
and some recursive method city_split(s)
to achieve what you want.
I have a string of key-value pairs, which unfortunately are separated by the same symbol. Is there a way to “just split” it into a list of tuples, without using a lambda?
Here is what i have:
Moscow|city|London|city|Royston Vasey|vilage
What i want:
[("Moscow","city"), ("London", "city")....]
This is a pretty easy one really…
first, split the string on '|'
then zip
every other element together:
data = s.split('|')
print zip(data[::2],data[1::2])
In python3, you’ll need: print(list(zip(data[::2],data[1::2]))
def group(lst, n):
for i in range(0, len(lst), n):
val = lst[i:i+n]
if len(val) == n:
yield tuple(val)
a = 'Moscow|city|London|city|Royston Vasey|vilage'
list(group(a.split('|'), 2))
The output is [('Moscow', 'city'), ('London', 'city'), ('Royston Vasey', 'vilage')]
s = 'Moscow|city|London|city|Royston Vasey|vilage'
it = iter(s.split('|'))
print [(x,next(it)) for x in it]
Python3:
>>> s = "Moscow|city|London|city|Royston Vasey|vilage"
>>> list(zip(*[iter(s.split('|'))]*2))
[('Moscow', 'city'), ('London', 'city'), ('Royston Vasey', 'vilage')]
Python2:
zip(*[iter(s.split('|'))]*2)
You could use city, status, remaining = s.split("|", 2)
and some recursive method city_split(s)
to achieve what you want.