假设你有这个列表
>>> L = ['00:00:10.000000, 500.000000000, 5.00000000, 80.00,\n',
... '00:00:10.002667, 500.000000000, 5.00000000, 80.00,\n']
您可以将每一行拆分为这样的列表
>>> [item.split() for item in L]
[['00:00:10.000000,', '500.000000000,', '5.00000000,', '80.00,'], ['00:00:10.002667,', '500.000000000,', '5.00000000,', '80.00,']]
但是您仍然需要进一步处理,并且由于每个字段的处理都不同,因此尝试在列表理解中完成所有操作会很尴尬和混乱。相反,首先编写一个辅助函数。我们就叫它“ process_item
”
>>> def process_item(item):
... return item.split()
...
>>> [process_item(item) for item in L]
[['00:00:10.000000,', '500.000000000,', '5.00000000,', '80.00,'], ['00:00:10.002667,', '500.000000000,', '5.00000000,', '80.00,']]
现在您可以更好地添加一些代码process_item
来处理您的各个字段
>>> def process_item(item):
... f1, f2, f3, f4 = item.split()
... f1 = f1.rstrip(',')
... f2 = f2.rstrip(',') # more code needed here
... f3 = f3.rstrip(',') # more code needed here
... f4 = f4.rstrip(',')
... return [f1, f2, f3, f4]
让我们看看如何修复 f2 和 f3
>>> f2 = '500.000000000'
>>> f2[:f2.find('.')+2]
'500.0'
.
但是如果f2中没有,你就不想这样做
>>> f2 = '500'
>>> f2[:f2.find('.')+2]
'5'
因此,您需要使用if
. 现在把它们放在一起
>>> def process_item(item):
... f1, f2, f3, f4 = item.split()
... f1 = f1.rstrip(',')
... f2 = f2.rstrip(',')
... f3 = f3.rstrip(',')
... f4 = f4.rstrip(',')
... if '.' in f2:
... f2 = f2[:f2.find('.')+2]
... if '.' in f3:
... f3 = f3[:f3.find('.')+2]
... return [f1, f2, f3, f4]
...
>>> [process_item(item) for item in L]
[['00:00:10.000000', '500.0', '5.0', '80.00'],
['00:00:10.002667', '500.0', '5.0', '80.00']]