遍历一个分成大块的列表

时间:2018-12-14 21:58:49

标签: python list for-loop

我有一个包含以下内容的分块列表:

ChunkedList = ['2018-12-14 15:00:00', 'A : aa1', 'B: bb2', 'C: cc3'] ['2018-12-14 16:00:00', 'A : aa2', 'B: bb2','C: cc1']['2018-12-14 17:00:00', 'A : aa3', 'B: bb1','C: cc3']['2018-12-14 18:00:00', 'A : aa3', 'B: bb1','C: cc3']['2018-12-14 19:00:00', 'A : aa3', 'B: bb1','C: cc3']['2018-12-14 20:00:00', 'A : aa3', 'B: bb1','C: cc3']

如果在未分类的列表上运行以下代码,则会得到包含相关时间的单行。

import datetime
hours = [(datetime.time(i).strftime('%H:%M:%S')) for i in range(6,18)]
WFList = [line for line in FullList if any(hour in line for hour in hours)] 

赞:

WFList= ['2018-12-14 15:00:00','2018-12-14 16:00:00','2018-12-14 17:00:00']

我当前对分块列表的代码是:

for chunk in ChunkedList:
    if any(hour in chunk for hour in hours):
        print(chunk) 

它什么也不返回。我想返回一个列表,其中包含以下范围内的时间:

IdealList = ['2018-12-14 15:00:00', 'A : aa1', 'B: bb2', 'C: cc3'] ['2018-12-14 16:00:00', 'A : aa2', 'B: bb2','C: cc1']['2018-12-14 17:00:00', 'A : aa3', 'B: bb1','C: cc3']

我通读了很多关于迭代和分块列表的文章,并感到困惑。任何和所有帮助表示赞赏!谢谢。

1 个答案:

答案 0 :(得分:1)

我相信问题在于hours严格包含时间。虽然您的列表同时包含datetime。您需要对字符串使用split方法来解析列表。试试这个:

import datetime

hours = [(datetime.time(i).strftime('%H:%M:%S')) for i in range(6,18)]

ChunkedList = [['2018-12-14 15:00:00', 'A : aa1', 'B: bb2', 'C: cc3'],
               ['2018-12-14 16:00:00', 'A : aa2', 'B: bb2','C: cc1'],
               ['2018-12-14 17:00:00', 'A : aa3', 'B: bb1','C: cc3'],
               ['2018-12-14 18:00:00', 'A : aa3', 'B: bb1','C: cc3'],
               ['2018-12-14 19:00:00', 'A : aa3', 'B: bb1','C: cc3'],
               ['2018-12-14 20:00:00', 'A : aa3', 'B: bb1','C: cc3']]

result = [big_list for big_list in ChunkedList if big_list[0].split()[1] in hours]
# [['2018-12-14 15:00:00', 'A : aa1', 'B: bb2', 'C: cc3'], ['2018-12-14 16:00:00', 'A : aa2', 'B: bb2', 'C: cc1'], ['2018-12-14 17:00:00', 'A : aa3', 'B: bb1', 'C: cc3']]

big_list[0].split()[1]仅在查看时查看其是否在hours中提供的范围内。