有一个嵌套列表A:
A = [[-1, 0, 1], [-2, 1, 9], [-3, 0, 7], [-4, 0, 5]]
如何检查 A 中的任何项目是否以 -1 ([-1, :, :]) 开头,如果是,则使用单个函数或方法而不是循环的索引是什么?
比方说,使用带有
list comprehension
和 next()
函数的单行代码。
index = next((i for i, sublist in enumerate(A) if sublist[0] == -1), None)
print(f"Index: {index}" if index is not None else "No items")
或者类似这样的事情,在
enumerate()
之后使用if else
A = [[-1, 0, 1], [-2, 1, 9], [-3, 0, 7], [-4, 0, 5]]
matching_indices = [index for index, sublist in enumerate(A) if sublist[0] == -1]
if matching_indices:
print("Found at indices:", matching_indices)
else:
print("No items found.")