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

2024-04-30 05:11:37 发布

您现在位置:Python中文网/ 问答频道 /正文

给定如下变量:

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

如何将其转换为嵌套的成对列表?i、 电子邮件:

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.

那我就不知道该怎么办,或者那是不是正确的一步


Tags: noaddressetconestorieslotalotfifty
1条回答
网友
1楼 · 发布于 2024-04-30 05:11:37

使用list comprehension分割每一行;我会使用^{} 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']]

相关问题 更多 >