简体   繁体   English

循环浏览字典中嵌入的列表列表中的所有项目

[英]Loop through all items in a list of list embedded in dictionary

I have dates in string form in list of lists in a dictionary. 我在字典中的列表列表中有字符串形式的日期。 I wrote a function to convert date strings to datetimes. 我编写了一个将日期字符串转换为日期时间的函数。 I would like to convert all string dates in my dictionary to date times. 我想将字典中的所有字符串日期都转换为日期时间。 My code only converts the first sublist in each table and it has no way of getting the others. 我的代码仅转换每个表中的第一个子列表,而无法获取其他子表。 What's the best way to do this? 最好的方法是什么?

import datetime

def parse_date(datestamp):
      try:
          return datetime.datetime.strptime(str(datestamp)[:10], '%Y-%m-%d')
      except ValueError:
          pass

My_Dict = {
    'Value1': {'Dates' : [['2014-10-14', 10, '2014-10-13', '2014-11-03'], ['2014-10-14', '2014-10-14', '2014-11-03']]},
    'Value2': {'Dates' : [['2014-10-14', '2014-10-13', '2014-11-03'], ['2014-10-14', '2014-10-14', '2014-11-03']]},
    }

for tbl in My_Dict:
    print [parse_date(x) for x in My_Dict[tbl]['Dates'][0]]

It's a matter of expanding out your nested lists correctly: 正确地扩展嵌套列表是一个问题:

for key in My_Dict:
    for data in My_Dict[key]["Dates"]:
        for date in data:
            print date, parse_date(date)

Gives: 给出:

2014-10-14 2014-10-14 00:00:00
2014-10-13 2014-10-13 00:00:00
2014-11-03 2014-11-03 00:00:00
2014-10-14 2014-10-14 00:00:00
2014-10-14 2014-10-14 00:00:00
2014-11-03 2014-11-03 00:00:00
2014-10-14 2014-10-14 00:00:00
10 None
2014-10-13 2014-10-13 00:00:00
2014-11-03 2014-11-03 00:00:00
2014-10-14 2014-10-14 00:00:00
2014-10-14 2014-10-14 00:00:00
2014-11-03 2014-11-03 00:00:00

To put this into a single flat list you could do: 要将其放入单个平面列表中,您可以执行以下操作:

print [parse_date(date) for key in My_Dict for data in My_Dict[key]["Dates"] for date in data]

but I think the three loops are much easier to read! 但是我认为这三个循环更容易阅读!

Nest your list comprehension as 将列表理解嵌套为

print [[parse_date(x) for x in i] for i in My_Dict[tbl]['Dates']]

But if you want a flat list, then you can try as Hooke mentioned, that is 但是,如果您想要一份简单的清单,则可以按照胡克(Hooke)所述尝试,那就是

print [parse_date(date) for key in My_Dict for data in My_Dict[key]["Dates"] for date in data]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM