【问题标题】:How to slice a list of strings till index of matched string depending on if-else condition如何根据 if-else 条件对字符串列表进行切片直到匹配字符串的索引
【发布时间】:2019-07-18 13:17:49
【问题描述】:

我有一个字符串列表 =

['after','second','shot','take','note','of','the','temp']

我想在“note”出现后删除所有字符串。 它应该返回

['after','second','shot','take']

还有一些列表没有标记词'note'。

所以如果是字符串列表 =

['after','second','shot','take','of','the','temp']

它应该按原样返回列表。 如何快速做到这一点?我必须对许多长度不等的列表重复同样的事情。

 tokens = [tokens[:tokens.index(v)] if v == 'note' else v for v in tokens]

【问题讨论】:

    标签: python-3.x string list for-loop if-statement


    【解决方案1】:

    可以切片列表时不需要迭代:

    strings[:strings.index('note')+1]
    

    s 是您输入的字符串列表。结束切片是独占的,因此 +1 确保 'note' 是一部分。

    如果数据丢失('note'):

    try:
        final_lst = strings[:strings.index('note')+1]
    except ValueError:
        final_lst = strings
    

    【讨论】:

    • 我编辑了我的问题。这仅在列表中存在标记的单词时才有效。如何也实现 if-else 条件?
    【解决方案2】:

    如果您想确保标记的单词存在:

    
        if 'note' in lst:
            lst = lst[:lst.index('note')+1]
    
    

    和上面@Austin 的回答差不多。

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 2017-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 2019-08-28
      • 1970-01-01
      相关资源
      最近更新 更多