python - 返回列表中元素的索引

标签 python list

class ModeBool():

    def __init__(self, mode):
        self.mode = mode

class IndexOfBool():

    def __init__(self, lst):
        '''
        Creates a list of True's as it's elements based on the given number.

        >>> i1 = IndexOfBool(5)

        Should create -> [True, True, True, True, True]
        '''
        self.lst = [ModeBool(True) for i in range(lst)]

    def bool_true(self):
        new_lst = []
        for index, element in enumerate(self.lst):
            if element is True:
                new_lst.append(index)
        return new_lst

但是,当我调用 bool_true 时,它不会返回正确的结果:

i1 = IndexOfBool(10)
i1.bool_true()
[]

它应该返回什么:

i1 = IndexOfBool(10)
i1.bool_true()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

不太确定为什么它没有返回预期的结果。另外,如果我用 ModeBool(False) 替换 ModeBool(True) ,那么它应该创建一个 False 列表。如果我在 False 列表上调用 bool_true ,它应该返回 []

最佳答案

这一行

self.lst = [ModeBool(True) for i in range(lst)]

应该是

self.lst = [ModeBool(True).mode for i in range(lst)]

关于python - 返回列表中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21338603/

相关文章:

Python - 列表组合

python - 在python3中组合两个列表

python - 根据元素距离交错两个 numpy 数组(python)

python - 监控 Chrome 中的下载过程

python - 排序的字典返回没有意义/python

list - 有效地将元素添加到python中的列表

css - 使用嵌套列表的 Wordpress css 导航菜单

mysql - 如何只获取列表中指定的项目?

python - 使用多个工作表创建多个 Excel 文件

python - Python 解析 300 MB 文件时出现内存错误