4 回答

TA贡献1757条经验 获得超8个赞
我们,程序员喜欢遵循DRY原则的代码(不要重复自己)
要获取 1 和 2 的更多 DRY 代码,而无需重复使用方块。
import math
int(math.sqrt(3.142) == 1
round(math.sqrt(3.142)) == 2
:)

TA贡献1818条经验 获得超3个赞
一种方法是在字符串之间来回转换:
# convert float to a string
num = 3.142
strnum = str(num)
# order the string lexicographically, using built-in method sorted
ordered = sorted(strnum)
# ordered = ['.', '1', '2', '3', '4']
# get the middle three elements at indices 1, 2, and 3, using a list slice
middle = ordered[1:4]
# middle = ['1', '2', '3']
# convert them into integers if desired, using a list comprehension
middle_ints = [int(e) for e in middle]
# middle_ints = [1, 2, 3]

TA贡献1812条经验 获得超5个赞
您可以使用运算符“%”并得到2。
int(3.142) = 3
int(3.142 % 3.142) = 2
int(3.142 / 3.142) = 1
添加回答
举报