Python:返回给定项目的二维列表中索引的 2 个整数
这周我一直在修改 python,但我遇到了一些问题。
如果我有一个像这样的二维列表:
myList = [[1,2],[3,4],[5,6]]
并且我这样做了,
>>>myList.index([3,4])
它会返回
1
但是,我想要其中一个列表中某个内容的索引,就像这样
>>>myList.index(3)
,它会返回
1, 0
有什么可以做到这一点吗?
干杯
I've been tinkering in python this week and I got stuck on something.
If I had a 2D list like this:
myList = [[1,2],[3,4],[5,6]]
and I did this
>>>myList.index([3,4])
it would return
1
However, I want the index of something in side one of the lists, like this
>>>myList.index(3)
and it would return
1, 0
Is there anything that can do this?
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
试试这个:
用法:
Try this:
Usage:
如果您进行多次查找,您可以创建一个映射。
If you are doing many lookups you could create a mapping.
使用简单的geneexpr:
示例
Using simple genexpr:
Example
目前还没有任何东西可以做到这一点,除非是在 numpy 中,而我对此不太了解。这意味着您必须编写代码来执行此操作。这意味着诸如“
[[1, 2], [2, 3], [3, 4]].index(3)
返回什么?”之类的问题。很重要。There is nothing that does this already, unless it's in numpy, which I don't know much about. This means you'll have to write code that does it. And that means questions like "What does
[[1, 2], [2, 3], [3, 4]].index(3)
return?" are important.这将返回子列表的多个实例(如果有)。
This will return more than one instance of the sub list, if any.
试试这个!这对我有用:)
Try this! this worked for me :)
根据kevpie的答案我设法获得了一个包含所有出现的坐标的2D列表
现在coordsList包含值1的所有索引我的列表:
Based on kevpie's answer I managed to get a 2D list containing the coordinates of all occurences
Now coordsList contains all indexes for value 1 in myList :
警告:
第一个答案是:
对于每个 x 中的任何 v,只要存在任何相等/相同的元素,就会导致很多错误。因为 x.index(v) 只返回 x 中具有相同 v 值的任何元素的第一个(最左边)索引,而不是当前 v 的实际索引。也就是说,仅当每行中的所有元素都有效时,这才有效是独一无二的。
相反,尝试这样做以避免非唯一值:
Caution:
The first answer up there:
will cause a lot of errors as long as there are any equal/identical elements, for any v in each x. Because x.index(v) only returns the first (leftmost) index of any element that has the same value of v, in x, NOT the actual index of the current v. That is, this only works if all elements in each row are unique.
Instead, try this to avoid non-unique values: