【问题标题】:Get the index of the first element in a list that is contained in another list? [duplicate]获取另一个列表中包含的列表中第一个元素的索引? [复制]
【发布时间】:2021-01-24 10:33:21
【问题描述】:

我有两个列表。一个是选定标点符号列表,另一个是标记列表。

punc = ['.', '!', '?']

tokens = ['today', 'i', 'went', 'to', 'the', 'park', '.', 'it', 'was', 'great', '!']

如何获取出现在标记中的第一个标点符号(由列表punc 定义)的索引?

在上述情况下,我想要的输出是 index = 6,因为出现的第一个标点符号是 '.'

【问题讨论】:

  • 你的问题解决了吗?
  • 是的!谢谢你们的帮助

标签: python


【解决方案1】:

您的问题的解决方案是这样的

punc = ['.', '!', '?']

tokens = ['today', 'i', 'went', 'to', 'the', 'park', '.', 'it', 'was', 'great', '!']

for i, element in enumerate(tokens):
    if element in punc:
        print(f"Found {element} at index: {i}")
        break

我们在这里所做的是使用 enumerate 遍历标记,它返回索引和元素。对于循环中的每次迭代,如果您找到了第一个元素,我们会检查元素是否在“punc”中。

【讨论】:

    【解决方案2】:

    您可以在tokens 列表中使用index() 这样做:

    punc = ['.', '!', '?']
    
    tokens = ['today', 'i', 'went', 'to', 'the', 'park', '.', 'it', 'was', 'great', '!']
    
    for p in punc:
        if p in tokens:
            print(p, tokens.index(p), sep=" index is: ")
        else:
            print(p, 'not found', sep=' ')
    

    此代码将打印标记中的所有 punc 索引(如果存在)。

    使用列表理解:

    [print(p, tokens.index(p), sep=" index is: ") if p in tokens else print(p, 'not found', sep=' ') for p in punc]
    

    输出:

    . index is: 6
    ! index is: 10
    ? not found
    

    如果您只想检查第一项而不是整个punc 列表:

    print(tokens.index(punc[0]) if punc[0] in tokens else 'not found')
    

    输出

    6
    

    使用[index()]可以在元素不在列表中时产生ValueError异常:

    Exception has occurred: ValueError
    '?' is not in list
    

    在您的情况下,? 中不存在 tokens 的值可能会发生这种情况。

    要解决这个问题,您有两种简单的方法:

    • 检查该项目是否在列表中,例如:'?' in tokens(这是干净/可红色的方法)
    • .index() 调用封装在try/except 中并对其进行管理。 (这是快速的方法)

    【讨论】:

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