如何在python中取数字的第n位数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39644638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:31:49  来源:igfitidea点击:

How to take the nth digit of a number in python

pythonint

提问by zakaria musa

I want to take the nth digit from an N digit number in python. For example:

我想从python中的N位数字中取出第n位数字。例如:

number = 9876543210
i = 4
number[i] # should return 6

How can I do something like that in python? Should I change it to string first and then change it to int for the calculation?

我怎么能在python中做这样的事情?我是否应该先将其更改为字符串,然后将其更改为 int 以进行计算?

采纳答案by Patrick Haugh

First treat the number like a string

首先将数字视为字符串

number = 9876543210
number = str(number)

Then to get the first digit:

然后得到第一个数字:

number[0]

The fourth digit:

第四位数字:

number[3]

EDIT:

编辑:

This will return the digit as a character, not as a number. To convert it back use:

这将返回数字作为字符,而不是数字。要将其转换回使用:

int(number[0])

回答by Chris Mueller

You can do it with integer division and remainder methods

您可以使用整数除法和余数方法来完成

def get_digit(number, n):
    return number // 10**n % 10

get_digit(987654321, 0)
# 1

get_digit(987654321, 5)
# 6

The //performs integer division by a power of ten to move the digit to the ones position, then the %gets the remainder after division by 10. Note that the numbering in this scheme uses zero-indexing and starts from the right side of the number.

//通过10的幂的整数除法进行的数字移动到的那些位置,则%通过10。注意得到余数,在本方案的编号使用从数的右侧的零索引和启动。

回答by Nathan Pyle

I would recommend adding a boolean check for the magnitude of the number. I'm converting a high milliseconds value to datetime. I have numbers from 2 to 200,000,200 so 0 is a valid output. The function as @Chris Mueller has it will return 0 even if number is smaller than 10**n.

我建议为数字的大小添加一个布尔检查。我正在将高毫秒值转换为日期时间。我有从 2 到 200,000,200 的数字,所以 0 是一个有效的输出。@Chris Mueller 所拥有的函数即使数字小于 10**n 也会返回 0。

def get_digit(number, n):
    return number // 10**n % 10

get_digit(4231, 5)
# 0


def get_digit(number, n):
    if number - 10**n < 0:
        return False
    return number // 10**n % 10

get_digit(4321, 5)
# False


You do have to be careful when checking the boolean state of this return value. To allow 0 as a valid return value, you cannot just use if get_digit:. You have to use if get_digit is False:to keep 0from behaving as a false value.

检查此返回值的布尔状态时,您必须小心。要允许 0 作为有效的返回值,您不能只使用if get_digit:. 您必须使用if get_digit is False:0避免表现为错误值。

回答by Shayaan

I was curious about the relative speed of the two popular approaches - casting to string and using modular arithmetic - so I profiled them and was surprised to see how close they were in terms of performance.

我很好奇这两种流行方法的相对速度 - 转换为字符串和使用模块化算法 - 所以我对它们进行了分析,并惊讶地发现它们在性能方面有多接近。

(My use-case was slightly different, I wanted to get all digits in the number.)

(我的用例略有不同,我想获取数字中的所有数字。)

The string approach gave:

字符串方法给出:

         10000002 function calls in 1.113 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.113    0.000    1.113    0.000 sandbox.py:1(get_digits_str)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

While the modular arithmetic approach gave:

虽然模块化算术方法给出了:


         10000002 function calls in 1.102 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.102    0.000    1.102    0.000 sandbox.py:6(get_digits_mod)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

There were 10000000 tests run with a max number size less than 10000000000000000000000000000.

运行了 10000000 次测试,最大数量小于 10000000000000000000000000000。

Code used for reference:

参考代码:

def get_digits_str(num):
    for n_str in str(num):
        yield int(n_str)


def get_digits_mod(num, radix=10):

    remaining = num
    yield remaining % radix

    while remaining := remaining // radix:
        yield remaining % radix


if __name__ == '__main__':

    import cProfile
    import random

    random_inputs = [random.randrange(0, 10000000000000000000000000000) for _ in range(10000000)]

    with cProfile.Profile() as str_profiler:
        for rand_num in random_inputs:
            get_digits_str(rand_num)

    str_profiler.print_stats(sort='cumtime')

    with cProfile.Profile() as mod_profiler:
        for rand_num in random_inputs:
            get_digits_mod(rand_num)

    mod_profiler.print_stats(sort='cumtime')

回答by GeekOverdose

Ok, first of all, use the str() function in python to turn 'number' into a string

好的,首先使用python中的str()函数将'number'转成字符串

number = 9876543210 #declaring and assigning
number = str(number) #converting

Then get the index, 0 = 1, 4 = 3 in index notation, use int() to turn it back into a number

然后得到索引,0 = 1, 4 = 3 用索引表示法,用 int() 把它变回数字

print(int(number[3])) #printing the int format of the string "number"'s index of 3 or '6'

if you like it in the short form

如果你喜欢它的简短形式

print(int(str(9876543210)[3])) #condensed code lol, also no more variable 'number'