簡體   English   中英

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

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

我試圖從日志文件中的一行文本中提取一些信息,該行有一些奇怪的分隔符,我可以使用split / replace / join等來解決這些問題。

當我嘗試將第二個時間元素拆分為“ - ”並將其添加回列表時,問題就出現了,我最終得到了一個子列表 - 這不是我想要的。

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())

結果是;

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

當我然后嘗試拆分'03959725-10:59:57.250.51222'時

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

我最終得到了;

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

我想要的是什么;

    ['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[3:4]=line1[3].replace('-', ' ').split()

它將用給定的序列替換切片​​:

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

如果你有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