Amatuer Ayers
Amatuer Ayers

Reputation: 39

How to convert a list of pairs into nested list?

Given a variable like:

stories = """adress:address
alot:a lot
athiest:atheist
noone:no one
beleive:believe
fivety:fifty
wierd:weird
writen:written"""

How would I go about converting it to a nested list of pairs? i.e:

new_stories = [['adress', 'address'], ['alot', 'a lot'], ['athiest', 'atheist'], ['noone', 'no one']] # etc.

I am currently doing this:

s = stories.split("\n")

which gives:

['adress:address', 'alot:a lot', 'athiest:atheist', 'noone:no one']  # etc.

Then I'm not sure what to do or if that's the right step at all.

Upvotes: 0

Views: 54

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123440

Use a list comprehension to split each line; I'd use the str.splitlines() method to produce the lines (as that covers more corner cases), and then str.split() to produce the per-line pair:

[s.split(':') for s in stories.splitlines()]

Demo:

>>> stories = """adress:address
... alot:a lot
... athiest:atheist
... noone:no one
... beleive:believe
... fivety:fifty
... wierd:weird
... writen:written"""
>>> [s.split(':') for s in stories.splitlines()]
[['adress', 'address'], ['alot', 'a lot'], ['athiest', 'atheist'], ['noone', 'no one'], ['beleive', 'believe'], ['fivety', 'fifty'], ['wierd', 'weird'], ['writen', 'written']]

Upvotes: 3

Related Questions