如果列表包含布尔值,如何从列表中获取整数的索引? [英] How to get the index of an integer from a list if the list contains a boolean?

查看:562
本文介绍了如果列表包含布尔值,如何从列表中获取整数的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用Python。

I am just starting with Python.

如果从列表中获取整数 1 的索引list在 1 之前包含一个布尔 True 对象?

How to get index of integer 1 from a list if the list contains a boolean True object before the 1?

>>> lst = [True, False, 1, 3]
>>> lst.index(1)
0
>>> lst.index(True)
0
>>> lst.index(0)
1

我认为Python认为 0 as False 1 as True 索引方法的参数中。如何获得整数 1 的索引(即 2 )?

I think Python considers 0 as False and 1 as True in the argument of the index method. How can I get the index of integer 1 (i.e. 2)?

在列表中以这种方式处理布尔对象背后的原因是什么?
从解决方案中我可以看出它并不那么简单。

Also what is the reasoning or logic behind treating boolean object this way in list? As from the solutions, I can see it is not so straightforward.

推荐答案

文档


列表是可变序列,通常用于存储
同类项目的集合(其中精确的相似程度将因
申请而异)。

Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application).

您不应将异构数据存储在列表中。
list.index 的实现仅使用 Py_EQ 执行比较( = = 运算符)。在您的情况下,比较返回truthy值,因为 True False 分别具有整数1和0的值(< a href =https://docs.python.org/3/library/functions.html#bool\"rel =nofollow> bool类毕竟是int的子类。

You shouldn't store heterogeneous data in lists. The implementation of list.index only performs the comparison using Py_EQ (== operator). In your case that comparison returns truthy value because True and False have values of the integers 1 and 0, respectively (the bool class is a subclass of int after all).

但是,您可以使用生成器表达式和内置 next 功能(从生成器获取第一个值),如下所示:

However, you could use generator expression and the built-in next function (to get the first value from the generator) like this:

In [4]: next(i for i, x in enumerate(lst) if not isinstance(x, bool) and x == 1)
Out[4]: 2

这里我们检查 x 是否是在比较 x 到1之前 bool 的实例。

Here we check if x is an instance of bool before comparing x to 1.

请记住 next 可以提高 StopIteration ,在这种情况下可能需要(重新)提高 ValueError (模仿 list.inde的行为x )。

Keep in mind that next can raise StopIteration, in that case it may be desired to (re-)raise ValueError (to mimic the behavior of list.index).

将此全部包装在一个函数中:

Wrapping this all in a function:

def index_same_type(it, val):
    gen = (i for i, x in enumerate(it) if type(x) is type(val) and x == val)
    try:
        return next(gen)
    except StopIteration:
        raise ValueError('{!r} is not in iterable'.format(val)) from None

一些例子:

In [34]: index_same_type(lst, 1)
Out[34]: 2

In [35]: index_same_type(lst, True)
Out[35]: 0

In [37]: index_same_type(lst, 42)
ValueError: 42 is not in iterable

这篇关于如果列表包含布尔值,如何从列表中获取整数的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆