Python break list values into sub-components and maintain key

守給你的承諾、 提交于 2019-12-12 06:47:23

问题


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.


回答1:


>>> 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']}


来源:https://stackoverflow.com/questions/20849134/python-break-list-values-into-sub-components-and-maintain-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!