我有这个清单:
[[10:09:56.033,ComponentB,2,DEBUG,description],
[10:09:56.034,ComponentB,1,DEBUG,description],
[10:09:57.034,ComponentB,2,DEBUG,description],
[10:09:57.045,ComponentB,2,DEBUG,description]]
如何打印所有时间戳。像:
10:09:56.033
10:09:56.034
10:09:57.034
10:09:57.045
另外,我如何每秒只打印时间戳,例如:
10:09:56.033
10:09:56.034
答案 0 :(得分:2)
您可以使用itertools.groupby
和datetime.strptime
:
from itertools import groupby
from datetime import datetime
def solve(item):
dt = datetime.strptime(item[0], '%H:%M:%S.%f')
return dt.hour, dt.minute, dt.second
lis = [['10:09:56.033', 'ComponentB', 2, 'DEBUG', 'description'], ['10:09:56.034', 'ComponentB', 1, 'DEBUG', 'description'], ['10:09:57.034', 'ComponentB', 2, 'DEBUG', 'description'], ['10:09:57.045', 'ComponentB', 2, 'DEBUG', 'description']]
for k, g in groupby(lis, key=solve):
print '\n'.join(x[0] for x in g) + '\n'
<强>输出:强>
10:09:56.033
10:09:56.034
10:09:57.034
10:09:57.045
datetime
对象转换的其他替代方法是使用str.partition('.')
(Suggested @jonclements:):
for k, g in groupby(lis, key=lambda x:x[0].partition('.')[0]):
print '\n'.join(x[0] for x in g) + '\n'
答案 1 :(得分:1)
打印所有邮票:
stamps = [
['10:09:56.033', 'ComponentB', 2, 'DEBUG', 'description'],
['10:09:56.034', 'ComponentB', 1, 'DEBUG,description'],
['10:09:57.034', 'ComponentB', 2, 'DEBUG,description'],
['10:09:57.045', 'ComponentB', 2, 'DEBUG,description']
]
for var in stamps:
print var[0]
至于每秒的打印(hcwhsa答案的变体,使用lambdas而不是单独的函数):
from itertools import groupby
lis = [['10:09:56.033', 'ComponentB', 2, 'DEBUG', 'description'],
['10:09:56.034', 'ComponentB', 1, 'DEBUG', 'description'],
['10:09:57.034', 'ComponentB', 2, 'DEBUG', 'description'],
['10:09:57.045', 'ComponentB', 2, 'DEBUG', 'description']]
for k, g in groupby(lis, key=lambda item: item[0][0:8]):
print k
print '\n'.join(x[0] for x in g) + '\n'
此应该更快。
答案 2 :(得分:0)
假设my_list
是您的列表,第一个元素是字符串
1
for item in my_list:
print item[0]
2
for item in my_list:
if item[0].startswith('10:09:56.'):
print item[0]