python - 为什么字典理解显示不同的值
问题描述
我想将字典理解应用于标题以及发布日期和趋势日期的差异。
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.......
我不确定为什么它会给出不同的值。我希望价值保持不变,对吗?
*注意函数的输入是视频类的对象
解决方案
这是因为 python 字典不是按顺序组织的。我可以向您保证,它们的价值是正确的,但订单有点混乱。您可以使用此代码来解决该问题
from collections import OrderedDict
def vid(videos):
dct = OrderedDict()
diff_date = [(x.trending_date - x.publish_date).days for x in videos]
for x in videos:
dct[x.title] = (x.trending_date - x.publish_date).days
print(diff_date)
print(dct)
这是一个订单字典。它需要更多空间,但可以使事情井井有条。欲了解更多信息,请查看这里
推荐阅读
- python - 如何在 pycharm venv 中安装软件包?
- c# - 如何在 C# 中循环切换函数
- android - 如何用另一个片段替换 nav_host_fragment 中的片段
- html - 在 HTML 中调整图像大小并保持 CSS 绝对正确
- reactjs - 为什么子 Styled-components 不应用样式?
- c++ - C++中的函数定义
- android-studio - 我想使用我在下面制作的导航栏更改我的颤振应用程序的屏幕
- c - GTK Hello World 抱怨未定义的引用
- angular - 将按钮动态添加到垫表角材料
- javascript - 如何使用 javascript 或 lodash 用新对象替换对象?