如何在 python 中从列表中拆分代码和日期?



我得到了一个python程序,里面有代码和日期的列表。例如,下面的列表中包含代码和日期。

List = ['10', '11', '11', '12', '2018-06-19 00:00:00', '2018-06-20 23:59:59']

我想将代码和日期分别拆分为两个不同的列表List_code其中将包含所有代码,List_Date将包含所有日期,如下所示。

List_Code = ['10', '11', '11', '12']
List_Date = ['2018-06-19 00:00:00', '2018-06-20 23:59:59']

我怎样才能做到这一点? 谢谢。

如果您的代码仅由数字组成,请使用str.isdigit来过滤它们。

lst = ['10', '11', '11', '12', '2018-06-19 00:00:00', '2018-06-20 23:59:59']
list_code = [x for x in lst if x.isdigit()]
# list_code:  ['10', '11', '11', '12']
list_date = [x for x in lst if not x.isdigit()]
# list_date ['2018-06-19 00:00:00', '2018-06-20 23:59:59']

您可以使用正则表达式来匹配日期字符串:

import re
List = ['10', '11', '11', '12', '2018-06-19 00:00:00', '2018-06-20 23:59:59']
def isDate(s):
return True if re.match('d{4}-d{2}-d{2} d{2}:d{2}:d{2}', s) else False
# Date strings:
List_Date = [x for x in List if isDate(x)]
# ['2018-06-19 00:00:00', '2018-06-20 23:59:59']
# Other strings:
List_Code = [x for x in List if not isDate(x)]
# ['10', '11', '11', '12']

最新更新