我该如何改进这段代码?
# 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我会用数学方法来做:
I'd do it mathematically:
它对负数做了一些明智的事情,不确定这是否是您想要的行为。
It does something sensible with negatives, not sure if that is the behaviour you want or not.
为什么一开始不这么说?
除非你还需要这些数字来做其他事情?
Why didn't you say so initially?
Unless you need the numbers for something else as well?
伪代码:
Pseudocode:
您的原始代码很接近,并且比一些简洁的表达式更容易阅读。您的代码存在一些小错误:在初始扫描中每次初始化
new_value
,而不是只初始化一次;并将 max_list 替换为计算出的标量,同时将其作为列表进行循环。在最后一行,您一定是想:
但是您删除了数组索引,这将用单个值替换列表。在循环的第二次迭代中,由于非列表中的索引无效,Python 将给出异常。
由于您的代码随着进展会产生越来越大的 new_value 值,因此我建议您不要在第一次扫描期间替换列表项。一旦计算出 new_value 的最终值,请进行第二次扫描:
请注意,我需要将 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 themax_list
with a calculated scalar while looping over it as a list.On the final line, you must have intended:
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:
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 ofnew_value
was starting over with each element, so your example would returnnew_value == 100
because this was based off the final element in the input list, which is 100.