有没有办法根据它们的属性更改列表中特定元素的数据类型?

huangapple go评论53阅读模式
英文:

Is there a way to change the data type of specific elements in a list based on their properties?

问题

让我们假设我有一个浮点数列表list1,其中加粗的部分是整数:

list1 = [1.8, 4.0, 3.2, 12.9, 18.0, 6.0, 7.6, 9.0]


现在,我想创建另一个列表list2,其中只包含list1中的整数部分:

list2 = [4, 18, 6, 9]



到目前为止,我尝试过类似这样的方法:

list1 = [1.8, 4.0, 3.2, 12.9, 18.0, 6.0, 7.6, 9.0]
list2 = filter(lambda item: type(item) == int, list1)
print(list(list2))

然而,代码仍然将整数部分的浮点数视为浮点数而不是整数。

是否有一种方法可以选择性地将列表中的整数部分浮点数转换为整数?
英文:

Let's assume I have a list1 of floats, where the ones in bold are whole numbers:

list1 = [1.8, **4.0**, 3.2, 12.9, **18.0**, **6.0**, 7.6, **9.0**]

I now want to make another list2 of only integers with only the whole number floats from list1:

list2 = [**4, 18, 6, 9**]

So far, I've tried something like this:

list1 = [1.8, 4.0, 3.2, 12.9, 18.0, 6.0, 7.6, 9.0]
list2 = filter(lambda item: type(item) == int, list1)
print(list(list2))

However, the code is still reading the whole number floats as floats rather than integers.

Is there a way to selectively convert the whole number floats into integers in the list?

答案1

得分: 1

你可以尝试:

list1 = [1.8, 4.0, 3.2, 12.9, 18.0, 6.0, 7.6, 9.0]

list2 = [int(x) for x in list1 if x.is_integer()]

#[4, 18, 6, 9]

你也可以这样做:

[int(x) for x in list1 if x % 1 == 0]  # 除以1得到的余数为0表示整数

#[4, 18, 6, 9]
英文:

You can try:

list1 = [1.8, 4.0, 3.2, 12.9, 18.0, 6.0, 7.6, 9.0]

list2 = [int(x) for x in list1 if x.is_integer()]

#[4, 18, 6, 9]

You can also do:

[int(x) for x in list1 if x%1 == 0]  #division by 1 will give 0 for integers

#[4, 18, 6, 9]

答案2

得分: 0

你可以使用这段代码:

list1 = [1.8, 4.0, 3.2, 12.9, 18.0, 6.0, 7.6, 9.0]
list2 = [int(num) for num in list1 if num == int(num)]
print(list2)

结果:

[4, 18, 6, 9]
英文:

You can use this code :

list1 = [1.8, 4.0, 3.2, 12.9, 18.0, 6.0, 7.6, 9.0]
list2 = [int(num) for num in list1 if num == int(num)]
print(list2)

Result:

[4, 18, 6, 9]

huangapple
  • 本文由 发表于 2023年2月8日 14:21:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定