【问题标题】:How to know the position of list? [duplicate]如何知道列表的位置? [复制]
【发布时间】:2019-02-21 13:56:00
【问题描述】:
 example: newlist = ["a,b,c","d","e","f","g"]

b 的位置是什么? 因为通常我们只是输入 newlist[0][1] 来查找列表的元素

【问题讨论】:

  • 'b' 没有位置,因为您的列表不包含元素 'b'。您应该更具体地了解您的需求。

标签: python python-3.x python-3.6


【解决方案1】:

你可以试试这样的:

search = 'b'
for i in newlist:
    for j in i:
        if j == search:
            print(str(i.index(search)) + str(newlist.index(i)))

这应该让你:0 1。但这仅在您有 2d 列表时才有效。

【讨论】:

    【解决方案2】:

    我们可以为此使用enumerate

    new_list = ["a,b,c","d","e","f","g"]
    
    for index, item in enumerate(new_list):
         print(index, item)
    
    (xenial)vash@localhost:~/python/stack_overflow$ python3.7 pos.py 
    0 a,b,c
    1 d
    2 e
    3 f
    4 g
    

    然后我们可以使用if 语句来检索index

    for index, item in enumerate(new_list):
        if 'b' in item:
            print(index)
    
    (xenial)vash@localhost:~/python/stack_overflow$ python3.7 pos.py 
    0
    

    【讨论】:

      猜你喜欢
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多