简体   繁体   English

在浮点数列表中仅将零更改为整数

[英]Change only zeros to integers in list of floats

I have this output from my code 我的代码有这个输出

[0.0, 0.0, 0.25, 0.5, 1.0],

but I need to make it be like this - 但我需要这样-

[0, 0, 0.25, 0.5, 1.0]

Any tips on how to change the zeros to integers? 关于如何将零更改为整数的任何提示?

If you want to change all zeros to integers, a simple list comprehension will do. 如果要将所有零都更改为整数,则可以执行简单的列表理解。

>>> lst = [0.0, 0.0, 0.25, 0.5, 1.0]
>>> [x or 0 for x in lst]
[0, 0, 0.25, 0.5, 1.0]

If and only if x == 0 then the expression will be evaluated to 0 . 当且仅当x == 0该表达式将被评估为0

This is assuming no other falsy values like empty strings or lists are in lst . 这是假设lst没有其他虚假值,例如空字符串或列表。

This is a bit of a weird request, but you can just do it on a case by case basis, turning all zeros into int s: 这是一个奇怪的请求,但是您可以根据具体情况进行处理,将所有零都转换为int

>>> output = [0.0, 0.0, 0.25, 0.5, 1.0]
>>> [int(x) if not x else x for x in output]
[0, 0, 0.25, 0.5, 1.0]

That list comprehension is the same as 列表理解与

new_list=[]
for x in output:
    if x == 0:
        new_list.append(int(x))
    else:
        new_list.append(x)

The for -loop form is easier for making more complicated replacement rules if you need to tweak it. 如果需要进行调整,则for loop形式更容易制定更复杂的替换规则。

You can simply do this by list comprehension : 您可以简单地通过列表理解来做到这一点:

Example : 范例:

If i want all the numbers that are less than 3 to be integers and rest float , then i would have done like this. 如果我希望所有小于3的数字都是整数并保持float ,则我将这样做。

myList = [1.1 , 2.7 , 7.8 ,8 ,8.9 ,3.2]
myList = [ int(i) if i < 3 else i for i in myList ]
print(myList)

Output: 输出:

[1, 2, 7.8, 8, 8.9, 3.2]

Your required code is : 您所需的代码是:

 myList = [0.0, 0.0, 0.25, 0.5, 1.0]
 myList = [int(i) if i == 0 else i for i in myList]
 print(myList)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM