比较“相似” Python 中的数字
为了同步我的 iPod 和本地音乐存储库,我使用其元数据为每个曲目创建了一个唯一的密钥。唯一轨道由轨道的以下元数据字段组成: 艺术家、专辑、曲目编号、持续时间。 iPod 以毫秒为单位保存曲目的持续时间,但我的本地存储库以秒为单位保存它。例如:iPod 上的 437590 毫秒在我的本地存储库中是 438 秒。
当我将 iPod 的曲目持续时间除以 1000 时,得到 437。我尝试使用 round()
,但 round (b.tracklen/1000)
打印 437
代码>.
如果没有匹配,我可以通过检查 math.ceil()
、math.floor()
的 iPod 持续时间来解决这个问题,但这是一个糟糕的解决方案。
解决这个问题的最佳方法是什么?
In order to sync my iPod and my local music repository, I created a unique key for each track using its metadata. The unique track consists of the track's following metadata fields:
artist, album, track number, duration. The iPod saves the track's duration in milliseconds, but my local repository saves it in seconds. For example: 437590 milliseconds on iPod is 438 seconds in my Local repository.
When I divide the ipod's track duration by 1000 I get 437. I tried using round()
, but round (b.tracklen/1000)
prints 437
.
I can hack this by checking math.ceil()
, math.floor()
for the iPod duration if there is no match but it's a lousy solution.
What is the best approach to this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的
round
调用给出了错误的结果,因为您除以 1000,而不是 1000.0Your
round
call is giving the wrong result as you're dividing by 1000, instead of 1000.0您正在体验 Python 2 的整数除法。当你除两个整数时,Python(和许多其他语言)会丢弃余数。正如 Dogbert 所指出的,您需要除以浮点数而不是整数。
You are experiencing Python 2's integer division. When you divide two integers, Python (and many other languages) throw away the remainder. You'll want to divide by a float instead of an integer, as Dogbert indicated.
对整数除法的结果进行舍入非常简单:
(n+(d/2))/d
。在你的情况下:Rounding the result of an integer division is very easy:
(n+(d/2))/d
. In your case:老实说,我认为您已经通过 Floor 和 ceil 调用将其钉牢了,但是为了简单起见,您可能需要执行 Floor((ipodtime/1000)+1) == localrepostime 来检查相等性,因为无论如何,ipod 时间似乎都会向下舍入。
Honestly, I think you nailed it already with the floor and ceil calls, but for somplicity you might want to do floor((ipodtime/1000)+1) == localrepostime to check equality since the ipod time seems to round down no matter what.