简体   繁体   English

Python:嵌套列表中元素的索引列表

[英]Python: Indexing list for element in nested list

I know what I'm looking for. 我知道我在找什么。 I want python to tell me which list it's in. 我想让python告诉我它在哪个列表中。

Here's some pseudocode: 这是一些伪代码:

item = "a"

nested_list = [["a", "b"], ["c", "d"]]

list.index(item) #obviously this doesn't work

here I would want python to return 0 (because "a" is an element in the first sub-list in the bigger list). 在这里我希望python返回0(因为“a”是较大列表中第一个子列表中的元素)。 I don't care which sub-element it is. 我不关心它是哪个子元素。 I don't care if there are duplicates, eg, ["a", "b", "a"] should return the same thing as the above example. 我不在乎是否有重复,例如,[“a”,“b”,“a”]应返回与上述示例相同的内容。

In Python 2.6 or better, 在Python 2.6或更高版本中,

next((i for i, sublist in enumerate(nested_list) if "a" in sublist), -1)

assuming eg you want a -1 result if 'a' is present in none of the sublists. 假设例如,如果没有任何子列表中存在'a'则需要-1结果。

Of course it can be done in older versions of Python, too, but not quite as handily, and since you don't specify which Python versions you're interested in, I think it's best to use the latest production-solid one (just edit your answer if you need to specify other, older versions of Python). 当然它也可以在旧版本的Python中完成,但不是很方便,因为你没有指定你感兴趣的Python版本,我认为最好使用最新的生产版本(只是如果您需要指定其他旧版本的Python,请编辑您的答案。

Edit : per request, let me try to explain how this work. 编辑 :根据请求,让我试着解释一下这是如何工作的。 I'm using the (new in 2.6) built-in function next , specifically I'm calling next(iterator, default) : returns the next item of the iterator (and thus the first, since this is the first time we're advancing that iterator), or the default value if the iterator's finished (which means "empty" if it's finished before we ever advanced it;-). 接下来使用(2.6中的新内置)内置函数,特别是我正在调用next(iterator, default) :返回迭代器的下一项(因此是第一项,因为这是我们第一次推进迭代器),或迭代器完成时的默认值(如果在我们提前它之前完成它意味着“空”;-)。 The default is clearly that -1 and gets returned if " a is present in none of the sublists", which means the same as "the iterator is empty" in this case. 默认值显然为-1 ,如果“ a在任何子列表中都不存在”,则返回,这意味着在这种情况下“迭代器为空”。

Let's look at the iterator again: 让我们再看一下迭代器:

(i for i, sublist in enumerate(nested_list) if "a" in sublist)

the (rounded) parentheses and for and if keywords mean this is a generator expression, also known for brevity as genexp. (圆形)括号和forif关键字意味着这是一个生成器表达式,也简称为genexp。 i (the index) and sublist (the item at that index) advance over enumerate(nested_list) -- if we didn't have enumerate here then we wouldn't be keeping track of the index, but in this case we do need it. i (索引)和sublist (该索引处的项目)超过enumerate(nested_list) - 如果我们没有enumerate ,那么我们就不会跟踪索引,但在这种情况下我们确实需要它。 They're only considered when the if clause is satisfied, that is, when the element you're looking for is present in the current sublist. 只有在满足if子句时才会考虑它们,也就是说,当您要查找的元素出现在当前子列表中时。

So this genexp produces, one at a time, each value of the index such that the sublist at that index satisfies the condition "a" in sublist . 因此,这个genexp一次一个地产生索引的每个值,使得该索引处的子列表满足子列表中的条件"a" in sublist Since we're using it inside next , we only take the first such index. 由于我们使用这里面next ,我们只取第一个这样的指标。

The OP might be justified for thinking that a magical builtin doing all of this in three or four characters would be handier -- and so it would, for this very specific requirement, which I believe I've never met before in over ten years of use of Python; OP可能有理由认为以三到四个字符完成所有这一切的神奇内置会更方便 - 因此,对于这个非常具体的要求,我认为我在十多年之前从未见过它。使用Python; however, if every such specific requirement had its own very specialized builtin the language and builtins would grown to be larger than the tax code. 但是,如果每个这样的特定要求都有自己非常专业的内置语言,那么内部增长将大于税码。 Instead, Python offers many lower-level "lego bricks" and a few handy way to snap them together, to clearly (and reasonably concisely) express the solution to a combinatorially-large variety of specific requirements, like the OP's. 相反,Python提供了许多较低级别的“乐高积木”和一些方便的方式将它们拼接在一起,以明确(并且合理地简明地)表达解决方案,以满足组合的各种特定要求,如OP。

You'll need to use a looping construct of some sort: 您需要使用某种循环结构:

next((sublist for sublist in mainlist if item in sublist))

That will give you a generator for all sublists containing the item you want, and give you the first one. 这将为您提供包含所需项目的所有子列表的生成器,并为您提供第一个。

Iterate over the list to get each sublist. 迭代列表以获取每个子列表。 Then, check to see if the item is in the sublist: 然后,检查项目是否在子列表中:

for i in range(0,len(list)):
    if whatYoureLookingFor in list[i]:
        print i
>>> nested_list = [["a", "b"], ["c", "d"]]
>>> item="a"
>>> for o,sublist in enumerate(nested_list):
...     if item in sublist:
...         print o
...
0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM