简体   繁体   English

如何在不创建子列表的情况下拆分python列表元素

[英]How do i split a python list element without creating a sublist

I am trying to extract some info from a line of text from a log file, the line has a few odd separators which I can get around with split/replace/join etc. 我试图从日志文件中的一行文本中提取一些信息,该行有一些奇怪的分隔符,我可以使用split / replace / join等来解决这些问题。

The issue comes when I try to then split the second time element at the '-' and add it back to the list, I end up with a sublist - which is not what I want. 当我尝试将第二个时间元素拆分为“ - ”并将其添加回列表时,问题就出现了,我最终得到了一个子列表 - 这不是我想要的。

line='2016-05-06T12:00:00.128189+01:00 mac-68c90b45b51e debug: 03959725-10:59:57.250[51222]*** NEW STATUS [3896374] : id=15 object=1 row=00408280 speed=0 crit=2 cell=130 intracell=512'

line1=(" ".join(line.split()).replace('[', '.').replace(']', ' ').strip().split())

Results in; 结果是;

['2016-05-06T12:00:00.128189+01:00', 'mac-68c90b45b51e', 'debug:', 03959725-10:59:57.250.51222', '***', 'NEW', 'STATUS', '.3896374', ':', 'id=15', 'object=1', 'row=00408280', 'speed=0', 'crit=2', 'cell=130', 'intracell=512']

When I then try to split '03959725-10:59:57.250.51222' with 当我然后尝试拆分'03959725-10:59:57.250.51222'时

line1[3]=line1[3].replace('-', ' ').split()

I end up with; 我最终得到了;

['2016-05-06T12:00:00.128189+01:00', 'mac-68c90b45b51e', 'debug:', ['03959725', '10:59:57.250.51222'], '***', 'NEW', 'STATUS', '.3896374', ':', 'id=15', 'object=1', 'row=00408280', 'speed=0', 'crit=2', 'cell=130', 'intracell=512']

What I would like is; 我想要的是什么;

    ['2016-05-06T12:00:00.128189+01:00', 'mac-68c90b45b51e', 'debug:', '03959725', '10:59:57.250.51222', '***', 'NEW', 'STATUS', '.3896374', ':', 'id=15', 'object=1', 'row=00408280', 'speed=0', 'crit=2', 'cell=130', 'intracell=512']

Any ideas on how to tidy up the way I do it? 关于如何整理我的方式的任何想法?

You can use slice assignment: 您可以使用切片分配:

line1[3:4]=line1[3].replace('-', ' ').split()

It will replace the slice with given sequence: 它将用给定的序列替换切片​​:

>>> l = [1, 2, 3, 4, 5]
>>> l[3:4] = ['new', 'items']
>>> l
[1, 2, 3, 'new', 'items', 5]

If you have Python3.5, there's also this fun way: 如果你有Python3.5,还有这种有趣的方式:

>>> a = [0, 1, 2, 'hello world whats up?', 4, 5]
>>> n = 3
>>> [*a[:n], *a[n].split(), *a[n+1:]]
[0, 1, 2, 'hello', 'world', 'whats', 'up?', 4, 5]

像这样重建列表:

line1 = line1[0:3] + line1[3].replace('-', ' ').split() + line1[4:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM