我该如何改进这段代码?

发布于 2024-09-08 07:59:50 字数 384 浏览 5 评论 0原文

# max_list = [83, 1350, 1, 100]
for i in range(len(max_list)):
     new_value = 1
     while new_value < max_list[i]:
          new_value *= 10
     max_list = new_value

我正在做的是将数字四舍五入到最接近的,呃,零填充值?我不确定它会被称为什么。但基本上,我想要 83 -> 100、1→ 1、 1350 --> 10000, 100 -> 10000, 100 -> 100. 我尝试使用 round() 函数,但无法让它执行我想要的操作。

这样做可以,但我认为可以用更少的行来写它。

# max_list = [83, 1350, 1, 100]
for i in range(len(max_list)):
     new_value = 1
     while new_value < max_list[i]:
          new_value *= 10
     max_list = new_value

What I'm doing is rounding numbers up to the closest, uhm, zero filled value? I'm not sure what it would be called. But basically, I want 83 -> 100, 1 -> 1, 1350 -> 10000, 100 -> 100. I tried using the round() function but couldn't get it to do what I wanted.

This does it but I thought it could be written in less lines.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

生生漫 2024-09-15 07:59:50

我会用数学方法来做:

from math import ceil, log10
int(pow(10, ceil(log10(abs(x or 0.1)))))

I'd do it mathematically:

from math import ceil, log10
int(pow(10, ceil(log10(abs(x or 0.1)))))
四叶草在未来唯美盛开 2024-09-15 07:59:50
def nextPowerOfTen(x):
  if x in [0, 1]:
     return x
  elif x < 1:
    return -nextPowerOfTen(abs(x))
  else:
    return 10**len(str(int(x) - 1))

>>> nextPowerOfTen(83)
100
>>> nextPowerOfTen(1350)
10000
>>> nextPowerOfTen(1)
1
>>> nextPowerOfTen(100)
100
>>> nextPowerOfTen(0)
0
>>> nextPowerOfTen(-1)
-1
>>> nextPowerOfTen(-2)
-10

它对负数做了一些明智的事情,不确定这是否是您想要的行为。

def nextPowerOfTen(x):
  if x in [0, 1]:
     return x
  elif x < 1:
    return -nextPowerOfTen(abs(x))
  else:
    return 10**len(str(int(x) - 1))

>>> nextPowerOfTen(83)
100
>>> nextPowerOfTen(1350)
10000
>>> nextPowerOfTen(1)
1
>>> nextPowerOfTen(100)
100
>>> nextPowerOfTen(0)
0
>>> nextPowerOfTen(-1)
-1
>>> nextPowerOfTen(-2)
-10

It does something sensible with negatives, not sure if that is the behaviour you want or not.

掐死时间 2024-09-15 07:59:50

我需要它是 1350 / 10000 = 0.135,所以它在 [0, 1] 范围内。

为什么一开始不这么说?

new_val = float("0." + str(old_val))

除非你还需要这些数字来做其他事情?

i need it to be 1350 / 10000 = 0.135 so it's in the [0, 1] range.

Why didn't you say so initially?

new_val = float("0." + str(old_val))

Unless you need the numbers for something else as well?

睫毛溺水了 2024-09-15 07:59:50
>>> x = 12345.678
>>> y = round(x)
>>> round(10 * y, -len(str(y)))
100000
>>> x = 12345.678
>>> y = round(x)
>>> round(10 * y, -len(str(y)))
100000
独孤求败 2024-09-15 07:59:50

伪代码:

div = input != 1 ? power(10,truncate(log10(abs(input))) + 1) : 1;
percent = input/div;

Pseudocode:

div = input != 1 ? power(10,truncate(log10(abs(input))) + 1) : 1;
percent = input/div;
夕色琉璃 2024-09-15 07:59:50

您的原始代码很接近,并且比一些简洁的表达式更容易阅读。您的代码存在一些小错误:在初始扫描中每次初始化 new_value,而不是只初始化一次;并将 max_list 替换为计算出的标量,同时将其作为列表进行循环。

在最后一行,您一定是想:

    max_list[i] = float(max_list[i]) / new_value

但是您删除了数组索引,这将用单个值替换列表。在循环的第二次迭代中,由于非列表中的索引无效,Python 将给出异常。

由于您的代码随着进展会产生越来越大的 new_value 值,因此我建议您不要在第一次扫描期间替换列表项。一旦计算出 new_value 的最终值,请进行第二次扫描:

max_list = [83, 1350, 1, 100]

# Calculate the required "normalizing" power-of-ten
new_value = 1.0
for i in range(len(max_list)):
    while new_value < max_list[i]:
        new_value *= 10.0

# Convert the values to fractions in [0.0, 1.0]
for i in range(len(max_list)):
    max_list[i] = max_list[i] / new_value

print max_list
# "[0.0083000000000000001, 0.13500000000000001, 0.0001, 0.01]"

请注意,我需要将 new_value 初始化为浮点值,以便生成浮点商。还有其他方法可以做到这一点,例如使用 float(max_list[i]) 检索用于标准化的值。 new_value 的原始计算是从每个元素开始的,因此您的示例将返回 new_value == 100 因为这是基于输入列表中的最终元素,即100.

Your original code was close, and more easily read than some terse expression. The problem with your code is a couple of minor errors: initializing new_value each time in the initial scan, rather than only once; and replacing the max_list with a calculated scalar while looping over it as a list.

On the final line, you must have intended:

    max_list[i] = float(max_list[i]) / new_value

but you dropped the array index, which would replace the list with a single value. On the second iteration of the loop, your Python would give an exception due to the invalid index into a non-list.

Because your code develops greater and greater values of new_value as it progresses, I recommend you not replace the list items during the first scan. Make a second scan once you calculate a final value for new_value:

max_list = [83, 1350, 1, 100]

# Calculate the required "normalizing" power-of-ten
new_value = 1.0
for i in range(len(max_list)):
    while new_value < max_list[i]:
        new_value *= 10.0

# Convert the values to fractions in [0.0, 1.0]
for i in range(len(max_list)):
    max_list[i] = max_list[i] / new_value

print max_list
# "[0.0083000000000000001, 0.13500000000000001, 0.0001, 0.01]"

Notice that I was required to initialize new_value as if it were a floating-point value, in order that it would result in floating-point quotients. There are alternative ways to do this, such as using float(max_list[i]) to retrieve the value for normalizing. The original calculation of new_value was starting over with each element, so your example would return new_value == 100 because this was based off the final element in the input list, which is 100.

剪不断理还乱 2024-09-15 07:59:50
from math import ceil, log10

# works for floats, too.
x = [83, 1350, 1, 100, 12.75]
y = [10**ceil(log10(el)) for el in x]

# alt list-comprehension if integers needed
# y = [int(10**ceil(log10(el))) for el in x]
from math import ceil, log10

# works for floats, too.
x = [83, 1350, 1, 100, 12.75]
y = [10**ceil(log10(el)) for el in x]

# alt list-comprehension if integers needed
# y = [int(10**ceil(log10(el))) for el in x]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文