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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2405928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:34:45  来源:igfitidea点击:

Python: Indexing list for element in nested list

pythonindexinglistnested

提问by aquateenfan

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). I don't care which sub-element it is. I don't care if there are duplicates, e.g., ["a", "b", "a"] should return the same thing as the above example.

在这里,我希望 python 返回 0(因为“a”是较大列表中第一个子列表中的一个元素)。我不在乎它是哪个子元素。我不在乎是否有重复,例如, ["a", "b", "a"] 应该返回与上面示例相同的内容。

回答by Alex Martelli

In Python 2.6 or better,

在 Python 2.6 或更高版本中,

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

assuming e.g. you want a -1result if 'a'is present in none of the sublists.

假设例如您想要一个-1结果 if'a'不存在于任何子列表中。

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;-). The default is clearly that -1and gets returned if "ais present in none of the sublists", which means the same as "the iterator is empty" in this case.

编辑:根据请求,让我尝试解释这是如何工作的。我正在使用(2.6 中的新功能)内置函数next,特别是我正在调用next(iterator, default):返回迭代器的下一项(因此是第一项,因为这是我们第一次推进该迭代器),或迭代器完成时的默认值(如果它在我们推进它之前完成,则意味着“空”;-)。默认值很明显,-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 forand ifkeywords mean this is a generator expression, also known for brevity as genexp. i(the index) and sublist(the item at that index) advance over enumerate(nested_list)-- if we didn't have enumeratehere then we wouldn't be keeping track of the index, but in this case we do need it. They're only considered when the ifclause is satisfied, that is, when the element you're looking for is present in the current sublist.

的(圆形)圆括号和forif关键字的意思是这是一个发电机表达,也称为为了简洁作为genexp。 i(索引)和sublist(该索引处的项目)前进enumerate(nested_list)——如果我们没有在enumerate这里,那么我们就不会跟踪索引,但在这种情况下我们确实需要它。只有在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. Since we're using it inside next, we only take the first such index.

所以这个 genexp 一次产生一个索引的每个值,使得该索引处的子列表满足条件"a" in sublist。由于我们在 inside 中使用它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; 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.

OP 可能有理由认为用三四个字符完成所有这些的神奇内置会更方便——因此,对于这个非常具体的要求,我相信我在十多年的时间里从未遇到过这样的要求。使用Python;但是,如果每个这样的特定要求都有自己非常专业的内置语言,并且内置代码会变得比税法更大。相反,Python 提供了许多较低级别的“乐高积木”和一些将它们组合在一起的便捷方法,以清楚地(并且相当简洁地)表达对组合大量特定需求的解决方案,例如 OP。

回答by sykora

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.

这将为您提供包含您想要的项目的所有子列表的生成器,并为您提供第一个。

回答by Mike Cialowicz

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

回答by ghostdog74

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