📜  Python| Python列表中非零元素的索引

📅  最后修改于: 2022-05-13 01:54:32.518000             🧑  作者: Mango

Python| Python列表中非零元素的索引

有时,在使用Python list 时,我们可能会遇到需要找到除 0 以外的所有整数的位置的问题。这可以应用于日间编程或竞争性编程。让我们讨论一下我们可以执行此特定任务的速记。

方法:使用enumerate() + 列表理解
该方法可以使用功能的组合来执行。在此,我们使用 enumerate函数来一起访问索引元素,列表推导用于迭代和逻辑创建。

# Python3 code to demonstrate working of
# Index of Non-Zero elements in Python list
# using list comprehension + enumerate()
  
# initialize list
test_list = [6, 7, 0, 1, 0, 2, 0, 12]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Index of Non-Zero elements in Python list
# using list comprehension + enumerate()
res = [idx for idx, val in enumerate(test_list) if val != 0]
  
# printing result
print("Indices of Non-Zero elements : " + str(res))
输出 :
The original list is : [6, 7, 0, 1, 0, 2, 0, 12]
Indices of Non-Zero elements : [0, 1, 3, 5, 7]