【问题标题】:Python: finding the index of a list into a list of listPython:将列表的索引查找到列表列表中
【发布时间】:2018-05-22 09:23:53
【问题描述】:

我是 python 的初学者,在将列表的索引搜索到另一个列表列表时遇到困难。我有两个列表 X 和 X_test。示例如下:

X = [[5 1 1 1 2 '1' 3 1 1],[5 4 4 5 7 '10' 3 2 1],[3 1 1 1 2 '2' 3 1 1],[6 8 8 1 3 '4' 3 7 1],[4 1 1 3 2 '1' 3 1 1]]

X_test = [[3 1 1 1 2 '2' 3 1 1],[6 8 8 1 3 '4' 3 7 1]]

X_test 的元素是列表 X 的一部分。现在,我想在 X 中找到 X_test 的每个完整列表的索引。

For eg. X_test[0] is at the index 2 of X and X_test[1] at index 3.

程序应该返回匹配列表的索引。即2 and 3

如何在 python 中做到这一点?提前致谢。

【问题讨论】:

  • XX_test 都有语法问题。

标签: python list loops


【解决方案1】:

您的代码没有完全运行,因为您需要在每个列表的元素之间使用逗号。

所以我写了我自己的例子。这是你可以做的:

X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
X_test = [[4, 5, 6]]
for i in X_test:
    print(X.index(i))

【讨论】:

    【解决方案2】:
    res = []
    for i in X_test:
        res.append(x.index(i))
    

    【讨论】:

      【解决方案3】:

      尝试使用.index()

      indexes = [X.index(test) for test in X_test]
      

      如果你尝试一个简单的列表(而不是列表的列表),整个事情会更清楚一些:

      >>> X = [0, 1, 4, 9, 16]
      >>> X_test = [9, 16]
      >>> indexes = [X.index(test) for test in X_test]
      
      [3, 4]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多