【问题标题】:Finding the index of an element of specific column in python list在python列表中查找特定列的元素的索引
【发布时间】:2021-07-16 17:06:05
【问题描述】:
table= [['','n','+','*','(',')','$'],
        ['E',1, -1, -1, 1, -1, -1],
        ['R',-1, 3, 2, -1, 2, 2],
        ['T',4, -1, -1, 4, -1, -1],
        ['S',-1, 5, 6, -1, 5, 5],
        ['F',7, -1, -1, 8, -1, -1]]

我想在第 1 列中使用 table.index() 函数查找“E”的索引,索引应该为 0。我怎样才能得到这个?

【问题讨论】:

标签: python list arraylist


【解决方案1】:

基本上逻辑工作首先将其转换为1d list,这可以使用python inbuilt功能或使用numpy modulereshape function轻松完成。然后使用t[0].index('E')找到索引,然后格式化结果(ind % 7, ind // 7))

代码:

方法一:

table= [['','n','+','*','(',')','$'],
        ['E',1, -1, -1, 1, -1, -1],
        ['R',-1, 3, 2, -1, 2, 2],
        ['T',4, -1, -1, 4, -1, -1],
        ['S',-1, 5, 6, -1, 5, 5],
        ['F',7, -1, -1, 8, -1, -1]]

c='F'
index=[(i, fruits.index(c)) for i, fruits in enumerate(table) if c in fruits]
print(index)

输出:

[(5, 0)]

方法二:

table = [['', 'n', '+', '*', '(', ')', '$'], ['E', 1, -1, -1, 1, -1, -1],
         ['R', -1, 3, 2, -1, 2, 2], ['T', 4, -1, -1, 4, -1, -1],
         ['S', -1, 5, 6, -1, 5, 5], ['F', 7, -1, -1, 8, -1, -1]]


import numpy as np

t = np.array(table).reshape(1, 42).tolist()
ind = t[0].index('E')
print(ind)
print('(Row_Number, Column_Number) = ', (ind % 7, ind // 7))

输出:

(Row_Number, Column_Number) =  (0, 1)

【讨论】:

    【解决方案2】:
    find = 'E'
    for row in range(len(table)):
        if find in table[row]:
            print(row, table[row].index(find))
    

    【讨论】:

      【解决方案3】:

      这里x 将等于包含“E”的第一行,然后您可以table.index(x) 将返回行索引,x.index(val) 将返回列索引。

      val = 'E'
            
      x = [x for x in table if val in x][0]
      
      print([table.index(x), x.index(val)]) 
      

      此解决方案将打印[1, 0]

      【讨论】:

      • 在表中使用 E 的想要 (X, Y) 对位置
      【解决方案4】:

      找到正确的子列表后,您可以在table 上使用index()。在列表中添加条件 if 'E' 以避免 ValueErrornext如果存在则返回第一个结果,否则默认None

      result = next(([table.index(t), t.index('E')] for t in table if 'E' in t), None)
      

      result 将是 [1, 0]

      【讨论】:

        猜你喜欢
        • 2021-06-25
        • 2017-11-11
        • 2016-02-29
        • 2019-11-11
        • 2020-12-05
        • 2023-03-24
        • 2013-07-26
        • 2019-03-03
        • 2010-12-02
        相关资源
        最近更新 更多