gpt4 book ai didi

python - 对基于 'if' 的列表元素进行子集化

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:04 24 4
gpt4 key购买 nike

我正在尝试提取列表中包含单词“FAILED”的元素的索引。

在我的应用程序中,我希望提取特定元素,因为我想应用一些正则表达式来获取有关 FAILED 状态的一些信息。

test_list = ["This is a test element", "This is a FAILED test element"]

if any("FAILED" for x in test_list):
failed = x
end_line = test_list.index(failed)
else:
end_line = test_list[-1]

print(end_line)

我希望 x == test_list[1] 或 x == 1.. 在我的应用程序中,我不知道会出现“FAILED”的位置的索引。

这是错误:NameError: name 'x' is not defined

最佳答案

试试这个:

test_list = ["This is a test element", "This is a FAILED test element", "x", "y"]

for i, x in enumerate(test_list):
if "FAILED" in x:
end_line = test_list[i]
break
else:
end_line = test_list[-1]

print(end_line)

输出

This is a FAILED test element

关于python - 对基于 'if' 的列表元素进行子集化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57148723/

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