【问题标题】:Sorting images by dates into a list from a dictionary按日期将图像排序到字典中的列表中
【发布时间】:2017-11-09 15:34:03
【问题描述】:

我知道我之前问过这个问题,但我仍然不确定为什么我在测试时得到一个空列表

def sorted_images(image_dict):
'''(dict) -> list of str

Given an image dictionary return a list of the filenames
sorted by date. 

>>> d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], \
'image2.jpg': ['UTSC', '2017-11-04', 'Happy Sat.']}
>>> sorted_images(d)    
['image1.jpg', 'image2.jpg']
'''
new_list = []
for filename, (location, date, caption) in image_dict.items():
    if filename not in image_dict:
        new_list.append(filename)
return new_list

【问题讨论】:

  • 首先是items,不是itmes..反正value_dict好像是list,不是dict
  • 好的,如何将最终结果放入列表并按日期对图像进行排序?
  • 因为image_dict 是一个字典,所以键是唯一的。在这种情况下,您只需要new_list = image_dict.keys()
  • 好的,我把它放在哪里?
  • 现在它说要解压的变量太多

标签: python python-3.x


【解决方案1】:

你的列表是空的,因为这个条件总是假的

if filename not in image_dict:

filenameimage_dict 中的一个键。

要获取文档字符串中指定的输出,您可以执行以下操作:

def sorted_images(image_dict):

    '''(dict) -> list of str

    Given an image dictionary return a list of the filenames
    sorted by date. 

    >>> d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], \
    'image2.jpg': ['UTSC', '2017-11-04', 'Happy Sat.']}
    >>> sorted_images(d)    
    ['image1.jpg', 'image2.jpg']
    '''
    return [k for k, v in sorted(image_dict.items(), key=lambda x: x[1][1])] 

【讨论】:

  • 好的,我该如何解决这个问题
  • new_list = [k for k in image_dict] 可能吗?我不知道你想做什么。
  • 我只想让我的代码与文档字符串匹配,并使其适用于文档字符串中的示例。
猜你喜欢
  • 1970-01-01
  • 2014-06-10
  • 2018-01-10
  • 2020-06-09
  • 2022-01-24
  • 1970-01-01
  • 2020-04-30
  • 2016-05-13
  • 1970-01-01
相关资源
最近更新 更多