[英]Efficient way get index of empty tuple with Python
目标是提取空元组的索引。 请问是否有比下面的代码更有效的方法。 对于实际情况,元组长度的大小比下面给出的要大。
tup=(('AT',), (), (), (), (), (), (), (), (), (), (), (), ('UR',), ('UR',),())
outpt= [idx for idx,i in enumerate(tup) if not i]
[1、2、3、4、5、6、7、8、9、10、11、14]
您的解决方案可能是一般情况下的最佳解决方案,但如果空元组不常见,则重复调用index()
可能更有效(取自https://thispointer.com/python-how-to-find-all -listes-of-an-item-in-a-list/ ):
def get_index_positions(list_of_elems, element):
''' Returns the indexes of all occurrences of give element in
the list- listOfElements '''
index_pos_list = []
index_pos = 0
while True:
try:
# Search for item in list from indexPos to the end of list
index_pos = list_of_elems.index(element, index_pos)
# Add the index position in list
index_pos_list.append(index_pos)
index_pos += 1
except ValueError as e:
break
return index_pos_list
您可以按如下方式使用
>>> get_index_positions(tup, ())
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14]
编辑:您也可以尝试numpy可能更快
>>> np.where(np.array(tup, dtype=object).astype(bool) == 0)
(array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14]),)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.