如何返回特定值对的索引?

2024-05-07 05:33:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从数组中找到特定值对的索引(行号)。下面是示例数组。你知道吗

A=[[357 131]
   [319 171]
   [229 196]
   [398 135]
   [242 148]
  ]

我想知道[229 196]和[242 148]的索引作为它们的行号

  3  and 5

我试着用

A.index ([229 196]) or A.index([229 196])

但不起作用。如何获取特定值对的行号?你知道吗


Tags: orand示例index数组行号
3条回答

你的语法错了。 你可能想从

A.index ([229 196])

A.index([229, 196])

您可能想看看documentation regarding arraysA应该这样定义:

>>> A=[[357,131],[319,171],[229,196],[398,135],[242,148]]

不过,关于如何访问数组元素的索引,您的猜测是对的:

>>> A.index([229,196])
2
>>> A.index([242,148])
4

小心,那些返回2和4,而不是3和5!实际上,数组的索引从0开始,而不是1!您可以通过执行A[0]来检查这一点。你知道吗

希望能有所帮助。你知道吗

您确定您的组件是ints的列表吗?[229 196]应该引发语法错误。你知道吗

如果您确实在使用int列表,那么以下操作应该可以工作:

A.index([229, 196])
A.index([242, 148])

否则请尝试:

A.index(["229 196"])

如果不确定类型,请尝试:

type(A[0])  # first item in list
type(A[0][0])  # first item within first item of list

相关问题 更多 >