我有一个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']
我如何才能做到这一点?谢谢。
发布于 2018-06-14 10:35:46
如果您的代码仅由数字组成,则使用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']
发布于 2018-06-14 10:21:46
您可以使用正则表达式来匹配日期字符串:
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']
https://stackoverflow.com/questions/50848702
复制相似问题