[英]What is the most efficient way of finding the index of an item from a list of lists and non-lists?
我有以下清单:
['F1', [10, 'r'], 'F2', 'F5', [15, 'w'] 'F3', [14, 'r'], 'F4']
我想要使用值15的列表[15, 'w']
的索引。
获取索引值的最有效方法是什么? (答案应该是4)
我尝试在 python .index()
函数中使用lambda x: x[0]
但无法找出任何有价值的东西。 我不想使用循环和 if 语句。 有没有办法使用 python 的内置功能有效地执行此任务?
每个列表的第一个值对于主列表中的所有列表都是唯一的。
编辑:
通过说“我不想使用循环”,我的意思是嵌套循环和 if 语句会增加解决方案的复杂性,因为我将在代码的许多地方使用非常大的列表。 所以只要复杂性没有大大增加,一个循环就可以了。
这里无法避免循环。 您的声明“我不想使用循环”应该替换为“我想将所有循环都推到 C 级别”。 但是,不幸的是,这是一个坏主意,因为您的数据类型不平衡。 虽然,我将演示我的矢量化(C 级)方法:
def cindex(x):
x = np.array(x, dtype='O') #forcing all the items to be 'object' type
f = np.vectorize(lambda x: isinstance(x, list)) #convert pyfunc to numpy accepted func
list_idx, = np.where(f(x)) #identify indices of x items that are lists
y = np.array(x[f(x)].tolist()) #filter y to contain only lists
equality_idx, = np.where(y[:,0]=='15') #identify indices of y where first item is '15'
return np.arange(len(x))[list_idx][equality_idx]
现在让我们将其与我认为在这种情况下是标准的 @AlexisG 解决方案进行比较。 使用具有 8000 个项目的输入运行它大约需要 2 2ms
(并且只有最后一个项目是正确的)。
[[10, 'r'], [15, 'w'], ...
总而言之,算法慢 3-4 倍,因此当您的数据类型不平衡时,请避免使用numpy
数组。
我知道有循环。 但我想用你的例子练习列表理解。
list_ = ['F1', [10, 'r'], 'F2', 'F5', [15, 'w'], 'F3', [14, 'r'], 'F4']
index = next((key for key, value in enumerate(list_) if type(value) == list for i_ in value if i_ == 15), None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.