如何将对列表转换为嵌套列表?

时间:2015-05-17 02:15:12

标签: python python-3.x

给出如下变量:

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

我如何将其转换为嵌套的对列表?即:

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

我目前正在这样做:

s = stories.split("\n")

给出:

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

然后,我不知道该怎么做,或者这是否是正确的步骤。

1 个答案:

答案 0 :(得分:3)

使用list comprehension分割每一行;我使用str.splitlines() method生成线条(因为它涵盖了更多的边角情况),然后使用str.split()生成每线对:

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

演示:

>>> 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']]
相关问题