列表列表中的Python搜索列表值

时间:2019-04-25 03:23:39

标签: python list

我遇到了这个问题:

searchTask = ["ST", "LOGIN", "BROWSE", "DOWNLOAD", "UPLOAD", "PING", "YOUTUBE", "FA", "BOOT"]
dateTime = "SCHEDULE: " + str(datetime.datetime.now().strftime("%H%M")) + "H"
finalList = []

for sublist in main_List:
    if dateTime in sublist:
       finalList.append(sublist[sublist.index(dateTime)])
       for x in searchTask:
           if x in sublist:
              finalList.append(sublist[sublist.index(x)])

这是main_List的值,它是一个具有列表值的列表,

[['SCHEDULE: 1509H', 'SCHEDULE: 1404H', 'ST: 1500', 'PING: www.google.com'], ['SCHEDULE: 1509H', 'SCHEDULE: 1700H', 'SCHEDULE: 2001H', 'ST: 1169', 'FA']]

我的问题是,如何在searchTask中搜索main_List的值,然后将这些值与计划时间一起附加到finalList。 我的finalList如要打印,例如:

finalList = [['SCHEDULE: 1509H', 'ST: 1500', 'PING: www.google.com' ],['SCHEDULE: 1509H', 'ST: 1169', 'FA']]

1 个答案:

答案 0 :(得分:1)

import datetime

main_List = [['SCHEDULE: 1509H', 'SCHEDULE: 1149H', 'ST: 1500', 'PING: www.google.com'], 
             ['SCHEDULE: 1509H', 'SCHEDULE: 1700H', 'SCHEDULE: 2001H', 'ST: 1169', 'FA']]

searchTask = ["ST", "LOGIN", "BROWSE", "DOWNLOAD", "UPLOAD", "PING", "YOUTUBE", "FA", "BOOT"]
dateTime = "SCHEDULE: " + str(datetime.datetime.now().strftime("%H%M")) + "H"
finalList = []

import re

pattern = "({}):".format("|".join(searchTask))
task_regex = re.compile(pattern)

for sublist in main_List:
    print dateTime
    if dateTime in sublist:
        finalList.append(dateTime)
        for e in sublist:
            if task_regex.search(e):
                finalList.append(e)