如何使用楼层划分返回浮动值

问题描述 投票:1回答:2

在Python 3中,我想返回整数值的单位,然后是数十,然后是数百等等。假设我有一个整数456,首先我要返回6,然后是5然后是4.有什么办法吗?我尝试了地板划分和循环,但没有奏效。

python-3.x floor-division
2个回答
0
投票

如果从文档中查看基本运算符列表,例如here

Operator    Description     Example
% Modulus   Divides left hand operand by right hand operand and returns remainder   b % a = 1
//  Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):    9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0

有了这些知识,您可以得到您想要的内容,如下所示:

In [1]: a = 456 

In [2]: a % 10 
Out[2]: 6

In [3]: (a % 100) // 10 
Out[3]: 5

In [4]: a // 100 
Out[4]: 4

0
投票

如果要根据需要在代码的不同位置检索数字,请编写生成器,如下所示。

如果您对Python的生成器不太熟悉,请快速查看https://www.programiz.com/python-programming/generator

»这里get_digits()是一个生成器。

def get_digits(n):
    while str(n):
        yield n % 10

        n = n // 10
        if not n:
            break

digit = get_digits(1729)

print(next(digit)) # 9
print(next(digit)) # 2
print(next(digit)) # 7
print(next(digit)) # 1

»如果您希望迭代数字,您也可以按如下方式进行迭代。

for digit in get_digits(74831965):
    print(digit)

# 5
# 6
# 9
# 1
# 3
# 8
# 4
# 7

»关于其用法的快速概述(在Python3的交互式终端上)。

>>> def letter(name):
...     for ch in name:
...         yield ch
... 
>>> 
>>> char = letter("RISHIKESH")
>>> 
>>> next(char)
'R'
>>> 
>>> "Second letter is my name is: " + next(char)
'Second letter is my name is: I'
>>> 
>>> "3rd one: " + next(char)
'3rd one: S'
>>> 
>>> next(char)
'H'
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.