gpt4 book ai didi

python - 从元组列表中获取 "NaN"的元组索引

转载 作者:行者123 更新时间:2023-12-04 08:13:32 28 4
gpt4 key购买 nike

我有一个元组列表,其中一个元素为 NaN :

l = [('a', 7.0), ('b', float('nan'))]
我想找到元组的索引 ('b', float('nan'))在上面的列表中。 l.index(('b', float('nan'))即使其索引为 1,也无法在列表中找到该元素。它正在引发 ValueError异常(exception)为:
>>> l.index(('b', float('nan'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: ('b', nan) is not in list
这很可能是因为每个 float('nan')是一个独立的 NaN 对象,这意味着两个元组也是不同的对象。
我一般如何解决这个问题?

最佳答案

float('nan') == float('nan')返回 False因为它被设计成不与自身匹配。这就是为什么list.index()函数无法找到 NaN 的匹配项值(value)并正在筹集ValueError异常(exception)。
请阅读 Why is NaN not equal to NaN?了解更多有关此行为的信息。
下面是一个自定义函数 check_nan_match()检查传递的对象是否具有相同的值。此函数将能够匹配 NaN对象也基于上述属性,即 NaN s 返回 False当与自身匹配时。

# Function too check passed values are match, including `NaN`
def check_nan_match(a, b):
return (b != b and a != a) or a == b
# ^ ^ `NaN` property to return False when matched with itself
获取 tuple的索引在 list包含 NaN ,在这里我创建另一个自定义函数为 get_nan_index .此函数接受 my_listmy_tuple作为参数,迭代 my_list获取 my_tuple 的索引.为了检查相等性,我使用以前创建的 check_nan_match能够匹配的函数 NaN值也是。
# Get index from list of tuple , when tuple is passed
def get_nan_index(my_list, my_tuple):
for i, t in enumerate(my_list):
if all(check_nan_match(x, y) for x, y in zip(t, my_tuple)):
return i
else:
raise ValueError # Raise `ValueError` exception in case of no match.
# Similar to `list.index(...)` function
示例运行:
# check for tuple with `NaN` 
>>> get_nan_index([('a', 7.0), ('b', float('nan'))], ('b', float('nan')))
1

# check for tuple without `NaN`
>>> get_nan_index([('a', 1), ('b', 2)], ('b', 2))
1

# `ValueError` exception if no match
>>> get_nan_index([('a', 7.0), ('b', 3)], ('b', float('nan')))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in get_nan_index
ValueError

关于python - 从元组列表中获取 "NaN"的元组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65826704/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com