【发布时间】:2020-10-17 16:40:20
【问题描述】:
我想将字典理解应用于标题以及发布日期和趋势日期的差异。
def vid(videos):
diff_date = [(x.trending_date - x.publish_date).days for x in videos]
dct = {x.title : (x.trending_date - x.publish_date).days for x in videos}
print(diff_date)
print(dct)
diff_date 的部分输出给出:
[1, 1, 2, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2361, 1, 8, 4, 2, 2, 207, 2, 1, 2, 1, 1, 2, 1, 3, 3, 2, 1, 4, 1, 4, 3, 2, 3, 4, 3, 4, 3, 2, 1, 3, 3, 1, 4, 4, 2, 4, 3, 4, 1, 4, 5, 3, 4, 3, 4, 4, 4, 4, 4, 28, 3, 4, 4, 2, 3, 3, 5, 5, 3, 4, 2, 4, 2, 5, 5, 4, 4, 4, 5, 4, 5, 5, 4, 5, 4, 4, 4, 4, 5, 4, 4, 4, 5, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 4, 4, 4, 5, 5, 6, 5, 4, 5, 4,....
dct 的部分输出给出:
{'WE WANT TO TALK ABOUT OUR MARRIAGE': 7, 'The Trump Presidency: Last Week Tonight with John Oliver (HBO)': 7, 'Racist Superman | Rudy Mancuso, King Bach & Lele Pons': 8, 'Nickelback Lyrics: Real or Fake?': 7, 'I Dare You: GOING BALD!?': 7, '2 Weeks with iPhone X': 7, 'Roy Moore & Jeff Sessions Cold Open - SNL': 6, '5 Ice Cream Gadgets put to the Test': 7, 'The Greatest Showman | Official Trailer 2 [HD] | 20th Century FOX': 2, 'Why the rise of the robots won’t mean the end of work': 2, "Dion Lewis' 103-Yd Kick Return TD vs. Denver! | Can't-Miss Play | NFL Wk 10 Highlights": 1,......
如您所见,dct 的值与diff_date 的输出值不同。我预期会发生的是:
{'WE WANT TO TALK ABOUT OUR MARRIAGE': 1, 'The Trump Presidency: Last Week Tonight with John Oliver (HBO)': 1, 'Racist Superman | Rudy Mancuso, King Bach & Lele Pons': 2, 'Nickelback Lyrics: Real or Fake?': 1, 'I Dare You: GOING BALD!?': 2.......
我不确定为什么它会给出不同的值。我希望价值保持不变?
*注意函数的输入是视频类的对象
【问题讨论】:
-
尝试比较
dct和[(x.name, (x.trending_date - x.publish_date).days) for x in videos],你会有所启发。 -
您是否重复提及相同的标题?如果是这样,后面的键值将覆盖前面的值
标签: python python-3.x dictionary list-comprehension