Python 将列表值分解为子组件并维护键 [英] Python break list values into sub-components and maintain key

查看:32
本文介绍了Python 将列表值分解为子组件并维护键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有一个列表如下:

['2925729', 'Patrick 没有和我们握手,也没有问我们的名字.他迅速而礼貌地向我们打招呼,但这似乎是例行公事.'].

我的目标是如下结果:

['2925729','Patrick 没有和我们握手,也没有问我们的名字'], ['2925729', '他迅速而礼貌地向我们打招呼,但这似乎是例行公事.']

非常感谢任何指针.

解决方案

>>>t = ['2925729', 'Patrick 没有和我们握手,也没有问我们的名字.他迅速而礼貌地向我们打招呼,但这似乎是例行公事.']>>>[ [t[0], a + '.'] for a in t[1].rstrip('.').split('.')][['2925729', 'Patrick 没有和我们握手,也没有问我们的名字.'], ['2925729', '他迅速而礼貌地向我们打招呼,但这似乎是例行公事.']]

如果你有一个很大的数据集并且想要节省内存,你可能想要创建一个生成器而不是一个列表:

g = ( [t[0], a + '.'] for a in t[1].rstrip('.').split('.') )对于关键,g 中的句子:# 做处理

生成器不会一次性创建所有列表.他们在您访问每个元素时创建它.这仅在您不需要一次使用整个列表时才有用.

附录:如果您有多个键,您询问了制作词典的问题:

<预><代码>>>>数据 = ['1', '我认为.我是.'], ['2', '我来了.我看见.我征服了.']>>>dict([ [t[0], t[1].rstrip('.').split('.')] for t in data ]){'1':['我认为','我是'],'2':['我来了','我看到了','我征服了']}

Hello I have a list as follows:

['2925729', 'Patrick did not shake our hands nor ask our names. He greeted us promptly and politely, but it seemed routine.'].

My goal is a result as follows:

['2925729','Patrick did not shake our hands nor ask our names'], ['2925729', 'He greeted us promptly and politely, but it seemed routine.']

Any pointers would be very much appreciated.

解决方案

>>> t = ['2925729', 'Patrick did not shake our hands nor ask our names. He greeted us promptly and politely, but it seemed routine.']
>>> [ [t[0], a + '.'] for a in t[1].rstrip('.').split('.')]
[['2925729', 'Patrick did not shake our hands nor ask our names.'], ['2925729', ' He greeted us promptly and politely, but it seemed routine.']]

If you have a large dataset and want to conserve memory, you may want to create a generator instead of a list:

g = ( [t[0], a + '.'] for a in t[1].rstrip('.').split('.') )
for key, sentence in g:
    # do processing

Generators do not create lists all at once. They create each element as you access it. This is only helpful if you don't need the whole list at once.

ADDENDUM: You asked about making dictionaries if you have multiple keys:

>>> data = ['1', 'I think. I am.'], ['2', 'I came. I saw. I conquered.']
>>> dict([ [t[0], t[1].rstrip('.').split('.')] for t in data ])
{'1': ['I think', ' I am'], '2': ['I came', ' I saw', ' I conquered']}

这篇关于Python 将列表值分解为子组件并维护键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆