【问题标题】:Index of list with 2 dimension python [duplicate]二维python列表的索引[重复]
【发布时间】:2015-12-22 06:13:51
【问题描述】:

任何人都可以帮助我,我有一个 2D 列表,我想知道 myList 在 2D 中的索引,但我只知道该索引的第一个值,例如我只知道 'a2' 并且我想知道列表的索引在第一个值中包含'a2',因为我想访问我想通过知道'a2' 访问['a2', 'b1'] 的列表示例:

myList2= [['a1', 'b2', 'c1'], ['a2', 'b1'], ['b1', 'c2'], ['b2', 'c1'], ['c1'], ['c2']]

其他情况....如果 myList2 是类点对象的列表。

【问题讨论】:

  • 另请参阅herehere,以及更多类似问题。

标签: python python-2.7


【解决方案1】:

您可以检查您知道的元素,在这种情况下'a2' 是否在任何嵌套列表中。如果是这样,您可以打印该列表。

>>> myList2= [['a1', 'b2', 'c1'], ['a2', 'b1'], ['b1', 'c2'], ['b2', 'c1'], ['c1'], ['c2']]
>>> for i in myList2:
    if 'a2' in i:
        print i


['a2', 'b1']
>>> 

【讨论】:

    【解决方案2】:

    这样就可以了:

    for element in [i for i in myList2 if i[0]=='a2']:
        #do something with element
    

    或者,

    for element in filter(lambda x:x[0]=='a2',myList2):
        #do something
    

    【讨论】:

    • @AvinashRaj,已编辑。
    • 当迭代找不到具有我设置的第一个值的列表时,我遇到了另一个问题。例如my list= [['a1', 'b2', 'c1'], ['b1', 'c2'], ['b2', 'c1'], ['c1'], ['c2']],我的代码是for element in [i for i in myList2 if i[0]=='a2']:。你能给我什么建议吗?
    • 在您的代码中,element 是一个列表。因此,您可以访问该列表的每个项目。您可以使用索引访问该列表的特定项目,或者如果您想遍历列表,您可以使用 for 循环。
    猜你喜欢
    • 2013-11-19
    • 2018-11-23
    • 2016-05-28
    • 2013-05-09
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 2017-03-28
    • 2020-06-11
    相关资源
    最近更新 更多