一直在使用Python列表
我是python新手。上周第一次开始使用它。到目前为止,我一直在快速提高速度,并在编码方面取得了良好的进展 我有一个包含字符串的列表变量(rawData)一直在使用Python列表,python,Python,我是python新手。上周第一次开始使用它。到目前为止,我一直在快速提高速度,并在编码方面取得了良好的进展 我有一个包含字符串的列表变量(rawData) rawData[0:2] ['00:00:10.000000, 500.000000000, 5.00000000, 80.00,\n', '00:00:10.002667, 500.000000000, 5.00000000, 80.00,\n'] 利用现有数据,我正在努力做到以下几
rawData[0:2]
['00:00:10.000000, 500.000000000, 5.00000000, 80.00,\n',
'00:00:10.002667, 500.000000000, 5.00000000, 80.00,\n']
利用现有数据,我正在努力做到以下几点:
rawData[0:2]
[['00:00:10.000000', '500.0', '5.0', '80.00'],
['00:00:10.002667', '500.0', '5.0', '80.00']]
谢谢你抽出时间。非常感谢。
split
是basestring
的所有实例都拥有的一种方法,它将字符串转换为字符串列表,在给定字符上进行拆分rstrip
将删除字符最右边的匹配项(删除尾随逗号)。试着这样做:
[ x.strip().rstrip(',').split(',') for x in rawData ]
假设你有这个清单
>>> 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\u 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']]
最全面的答案。标准化“整数”字符串格式的另一种方法可能是将其转换为浮点,并使用字符串格式说明符指定句点后的适当位数,以将其转换回适当的字符串。首先,这将取消对“.”的检查。第二,如果找不到“.”,它会将其添加到。。。如果这是OP.Third的意图,那么您不必假设在这段时间之后会有足够的“0”。唯一的假设是最后3个字符串可以转换为浮点数。
>>> 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']]