获取python中的最高有效位 [英] Get most significant digit in python

查看:74
本文介绍了获取python中的最高有效位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有清单 [34523、55、65、2]

获取最有效数字的 [3,5,6,2] 的最有效方法是什么?如果可能的话,不更改每个 str()?

What is the most efficient way to get [3,5,6,2] which are the most significant digits. If possible without changing changing each to str()?

推荐答案

假设您只处理正数,则可以将每个数字除以小于该数字的10的最大幂,然后取下结果.

Assuming you're only dealing with positive numbers, you can divide each number by the largest power of 10 smaller than the number, and then take the floor of the result.

>>> from math import log10, floor
>>> lst = [34523, 55, 65, 2]
>>> [floor(x / (10**floor(log10(x)))) for x in lst]
[3, 5, 6, 2]

如果您使用的是Python 3,则可以使用整数除法运算符//:

If you're using Python 3, instead of flooring the result, you can use the integer division operator //:

>>> [x // (10**floor(log10(x))) for x in lst]
[3, 5, 6, 2]

但是,我不知道这是否比转换成字符串并分割第一个字符更有效.(请注意,如果要处理0到1之间的数字,则需要稍微复杂一些.)

However, I have no idea whether this is more efficient than just converting to a string and slicing the first character. (Note that you'll need to be a bit more sophisticated if you have to deal with numbers between 0 and 1.)

>>> [int(str(x)[0]) for x in lst]
[3, 5, 6, 2]

如果这是对性能至关重要的代码,则应该测量这两个选项,然后看看哪一个更快.如果它不在性能至关重要的代码段中,请使用您最容易理解的代码.

If this is in a performance-critical piece of code, you should measure the two options and see which is faster. If it's not in a performance-critical piece of code, use whichever one is most readable to you.

这篇关于获取python中的最高有效位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆