num = int(input("Please give me a number: "))
print(num)
thou = int((num // 1000))
print(thou)
hun = int((num // 100))
print(hun)
ten =int((num // 10))
print(ten)
one = int((num // 1))
print(one)
我尝试了这个方法,但它没有起作用,我陷入困境。
num = int(input("Please give me a number: "))
print(num)
thou = int((num // 1000))
print(thou)
hun = int((num // 100))
print(hun)
ten =int((num // 10))
print(ten)
one = int((num // 1))
print(one)
我尝试了这个方法,但它没有起作用,我陷入困境。
你可能想要尝试类似以下的内容:
def get_pos_nums(num):
pos_nums = []
while num != 0:
pos_nums.append(num % 10)
num = num // 10
return pos_nums
然后按照以下方式调用此方法。
>>> get_pos_nums(9876)
[6, 7, 8, 9]
0th
索引将包含单位,1st
索引将包含十位,2nd
索引将包含百位,以此类推...
这个函数会在负数的情况下失败。我把处理负数的任务交给你作为一个练习。
a = str(input('Please give me a number: '))
for i in a[::-1]:
print(i)
演示:
Please give me a number: 1324
4
2
3
1
num = 1234
thousands = num // 1000
hundreds = (num % 1000) // 100
tens = (num % 100) // 10
units = (num % 10)
print(thousands, hundreds, tens, units)
# expected output: 1 2 3 4
"//"在Python中表示整数除法,它会从浮点数中大量去除小数部分并返回一个整数。
例如:
4/3 = 1.333333
4//3 = 1
def get_place_values(n):
return [int(value) * 10**place for place, value in enumerate(str(n)[::-1])]
例如:
get_place_values(342)
>>> [2, 40, 300]
Next, you could write a helper function:
def get_place_val_to_word(n):
n_str = str(n)
num_to_word = {
"0": "ones",
"1": "tens",
"2": "hundreds",
"3": "thousands"
}
return f"{n_str[0]} {num_to_word[str(n_str.count('0'))]}"
def print_place_values(n):
for value in get_place_values(n):
print(get_place_val_to_word(value))
例如:
num = int(input("Please give me a number: "))
# User enters 342
print_place_values(num)
>>> 2 ones
4 tens
3 hundreds
num=1234
digit_at_one_place=num%10
print(digit_at_one_place)
digits_at_tens_place=(num//10)%10
digits_at_hund_place=(num//100)%10
digits_at_thou_place=(num//1000)%10
print(digits_at_tens_place)
print(digits_at_hund_place)
print(digits_at_thou_place)
最快的方法:
num = str(input("Please give me a number: "))
print([int(i) for i in num[::-1]])
我必须对数组的许多值进行此操作,而且它并不总是以十进制(正常计数-您的十位、百位、千位等)为基础。因此,参考点略有不同:1=第一位(个位),2=第二位(十位),3=第三位(百位),4=第四位(千位)。因此,您的矢量化解决方案:
import numpy as np
def get_place(array, place):
return (array/10**(place-1)%10).astype(int)
速度快,还可以处理不同进制的数组。
# method 1
num = 1234
while num>0:
print(num%10)
num//=10
# method 2
num = 1234
print('Ones Place',num%10)
print('tens place',(num//10)%10)
print("hundred's place",(num//100)%10)
print("Thousand's place ",(num//1000)%10)
这将完成它,完全不使用字符串,并合理处理传递给col
的任何整数。
def tenscol(num: int, col: int):
ndigits = 1
while (num % (10**ndigits)) != num:
ndigits += 1
x = min(max(1, col), ndigits)
y = 10**max(0, x - 1)
return int(((num % 10**x) - (num % y)) / y)
用法:
print(tenscol(9785,-1))
print(tenscol(9785,1))
print(tenscol(9785,2))
print(tenscol(9785,3))
print(tenscol(9785,4))
print(tenscol(9785,99))
输出:
5
5
8
7
9
9
def get_pos(num,unit):
return int(abs(num)/unit)%10
因此,在“个位数”中,单位是1,而在“十位数”中,单位是10,以此类推。
它可以有效地处理任何数字,甚至包括负数。
所以,给定数字256,要获取十位数中的数字,则执行以下操作:
get_pos(256,10)
>> 5