python - 查找列表中的特定值

标签 python list

大家好,我的部分代码遇到了一些小问题

例如,如果

target_list = []
lst = [1, 2, 3, 4, 4, 5, 4]
target = 4
if target in lst:
    target_list.append(lst.index(target))
return target_list

我希望它返回:

[3, 4, 6]

我认为问题与 .index(target) 仅采用列表的第一个目标有关。谢谢

最佳答案

您可以使用enumerate来跟踪索引,并使用列表理解和if来过滤和提取与特定值相对应的索引:

[i for i, v in enumerate(lst) if v == 4]
# [3, 4, 6]

使用普通循环,您需要初始化索引列表,并在值为 target 时将索引附加到该列表:

index = []
for i in range(len(lst)):
    if lst[i] == 4:
        index.append(i)

index
# [3, 4, 6]

关于python - 查找列表中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42686733/

相关文章:

python - 在Python中访问列表列表的每个列表的内容

list - 在线性时间内反转排列,仅使用列表

python - 为什么我的装饰器会破坏这个 Flask-Login 端点?

Python:将函数应用于groupby

python - 用树木森林建模字符串序列

python - 如何编写一个可调用 View 以在 Pyramid 中显示静态 html 文件?

java - 如何交换 ArrayList 中两个对象的位置?

python - 如果满足条件,如何只调用列表中的字典值?

python - 将python sql列表转换为字典

python - 在长时间运行的 Python 进程中迭代大型数据集 - 内存问题?