【问题标题】:How to return the index of an element in a list of lists?如何返回列表列表中元素的索引?
【发布时间】:2021-09-08 03:08:02
【问题描述】:
List = [[1,2,3],[4,5,6],[7,8,9]]

我想在List 中选择一个随机元素并返回它的索引。

当我这样做时:

List.index(random.choice(List[random.randint(0,2)]))

这显然给了我一个错误,因为代码只索引List 中的列表元素。

我想要的是这样的:

output: The random number is: 4 and the index is: (1,0) or List[1][0]

【问题讨论】:

  • 您已经清楚地发现了逻辑中的缺陷——4 不在List 中。您需要遍历List 的元素并找到包含4 的元素。你试过这样做吗?
  • 既然元素是随机选择的,那为什么不反过来——选择随机索引获取随机元素呢?
  • @PranavHosangadi 我发布了我找到的解决方案。我想你是这个意思?
  • @pjs 是真的 xD

标签: python-3.x random indexing


【解决方案1】:

在 python3.x 列表文档的 .index() 部分中,您将看到,index 方法返回“列表中第一项的值等于搜索元素的从零开始的索引”。在您的情况下,列表中的所有元素都是列表。 要获取包含搜索编号的列表索引及其在该列表中的位置,您必须执行以下操作:

List = [[1,2,3],[4,5,6],[7,8,9]]
el = random.choice(List[random.randint(0,len(List))])
result = [(y, List[y].index(el)) for y, _ in enumerate(List) if (el in List[y])]

【讨论】:

  • 这很好用! _ 在循环中代表什么? ...它只是一个占位符吗?
  • "_" 是一次性变量的占位符。
  • 为什么要丢弃enumerate()返回的值,然后索引到List?只需执行for y, val in enumerate(List),然后使用val 而不是List[y]
  • 我使用 List[y] 而不是使用 enumerate 的第二个变量来强调我们正在查看列表的 y 索引。在 val 上使用 .index() 也可以。感谢@PranavHosangadi 的建议
【解决方案2】:

我想出了这个。不知道方便不。我觉得应该有更好的解决方案xD

tuple = (0, 0)
num = random.choice(List[random.randint(0,2)])
for i in List:
    if num in i:
        print(f"the random number is {num} and the index is {List.index(i), i.index(num)}")

output: the random number is 9 and the index is (2, 2)

【讨论】:

  • 这是一个很好的开始!一些注意事项: 1. tuple 已经意味着一些东西,所以你可能想把它命名为别的,以避免遮蔽内置的 tuple 类。 2. 查看enumerate() 函数——这将允许您使用索引和值遍历集合,因此您无需再次调用List.index()。 3.if num in i需要遍历整个列表i来查找num是否存在于其中。然后i.index() 需要做同样的事情来找出它在列表中的位置。相反,您可以有另一个循环,例如外循环,以便一次性完成。
  • @PranavHosangadi 在@SaiKiran 的评论之后,我发现了 enumerate() 函数 rn。我明白了......我会尝试你的下一个提示。非常感谢!
【解决方案3】:

将给定的列表视为二维数组,即矩阵

import random
# Userinput rows = int(input());matrix = [list(map(int,input().split())) for ctr in range(rows)]
matrix = [[1,2,3],[4,5,6],[7,8,9]]
rowIndex = random.randint(0, len(matrix) - 1)
colIndex = random.randint(0, len(matrix[rowIndex]) - 1)
print(f"The random number is: {matrix[rowIndex][colIndex]} and the index is: {(rowIndex, colIndex)} or matrix[{rowIndex}][{colIndex}]")

【讨论】:

    【解决方案4】:

    这应该适用于List 中的任何尺寸列表,而不仅仅是尺寸 3。

    import random
    
    List = [[1,2,3],[4,5,6],[7,8,9]]
    
    rand1 = random.randint(0, len(List)-1)
    rand2 = random.randint(0, len(List[rand1]-1))
    
    print("The random number is: {} and the index is: {}".format(List[rand1][rand2], (rand1, rand2)))
    

    输出:The random number is: 6 and the index is: (1, 2)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      相关资源
      最近更新 更多