2016-02-19 85 views

回答

1

您可以很容易地使用split()字符串方法。一个简单的例子:

eta='12:34:56' #this is a string 
splitted=eta.split(':') 

和结果(splitted)是以下列表:

['12', '34', '56'] 

,你可以很容易地通过列表索引访问:小时部分(12)将splitted[0],纪要部分(34)将为splitted[1],秒部分(56)将为splitted[2]

如果您有一个小时的列表,只需使用for-loop迭代该列表,并将split()方法应用于列表的每个元素。比方说,我们的名单是:

hoursList=['12:34:56','78:90:12'] 

,你可以这样做

for item in hoursList: 
    splitted=item.split(':') 
    print splitted[0] 

这个代码将打印出

12 
78 

是,的确,在字符串的小时部分hoursList

+0

你能否告诉我如何将它存储在字典中,以便我可以将某些“hh”作为一个键以及它发生的次数作为值? –

+0

*键*值是小时(在这种情况下是'splitted [0]')。如果你第一次遇到这样的值('如果splited [0] not in dictionary.keys()'或类似的东西),* value *初始化为'1',如果已经存在,你只需增加这个值。向我离开Charles Severance问好。 – Alessiox

+0

此链接也有帮助:http://meta.programmers.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems – Alessiox

1

这应该工作:

time = "hh:mm:ss".split(":") 
print(time[0]) 

希望它能帮助!

0

使用正则表达式的每个列表元素上:(\ d {2}):\ d {2}:\ d {2}

相关问题