如何添加不以日期python 3开头的列表?

时间:2019-06-17 07:13:17

标签: python

如何添加不以日期python 3开头的列表?

添加不是以日期开头的子列表

import  re
from datetime import datetime
l = [["01/01/2001","words1"],["words2","words3"],["words4"],["03/03/2003","words5","words6"],["words7"]]


def extract_description_words_bet_date_date(nn_lst):
    date_list = []
    str_list = []

    for elem in nn_lst:
        try:
            datetime.strptime(elem[0], "%d/%m/%Y")
            date_list.append(elem)
        except ValueError:
            str_list.append(elem)
            pass
    return str_list

list2 = extract_description_words_bet_date_date(l)

print(list2)

预期输出:[["01/01/2001","words1"],["words2","words3","words4"],["03/03/2003","words5","words6"],["words7"]]

实际输出:[['words2', 'words3'], ['words4'], ['words7']]

1 个答案:

答案 0 :(得分:1)

即使问题不是很清楚,这也是您可能正在寻找的解决方案

from datetime import datetime
l = [["01/01/2001","words1"],["words2","words3"],["words4"],["03/03/2003","words5","words6"],["words7"]]


def extract_description_words_bet_date_date(nn_lst):
    new_list = []

    for elem in nn_lst:
        try:
            datetime.strptime(elem[0], "%d/%m/%Y")
            new_list.append(elem)
        except ValueError:
            try:
                if len(new_list) == 0:
                  new_list.append(elem)
                else:
                  datetime.strptime(new_list[-1][0], "%d/%m/%Y")
                  new_list.append(elem)
            except ValueError:
                new_list[-1] = new_list[-1] + elem
                pass
    return new_list

list2 = extract_description_words_bet_date_date(l)

print(list2)