【问题标题】:selecting suitable options from list of strings从字符串列表中选择合适的选项
【发布时间】:2019-10-21 11:33:31
【问题描述】:

我有一个句子列表。例如:

x = ['Mary had a little lamb', 
           'Jack went up the hill', 
           'Jill followed suit',    
           'i woke up suddenly',
           'I just missed the train',
           'it was a really bad dream']

我想选择倒数第二个单词不是“the”的选项。 我怎么能在 python 3 上做到这一点? 我试过这个:

l = []
for i in x:
    for k in i: 
        if i.index(k) != (len(i) -2):
             l.append(' '.join(i))

我在小列表上工作,但不在大列表上(几千个元素)

【问题讨论】:

  • 请展示您的尝试。
  • 您的代码是如何“工作”的?它甚至没有"the"。将每个字符串的len(i)-1“间隔”副本添加到结果列表似乎是一种非常低效的方法。
  • 它的部分代码,我也有一个不应该是倒数第二个单词的列表

标签: python python-3.x loops select


【解决方案1】:

您可以使用split 的列表推导将句子分成单词,然后使用索引[-2] 检查倒数第二个元素。

>>> [s for s in x if s.split()[-2] != "the"]
['Mary had a little lamb',
 'Jill followed suit',
 'i woke up suddenly',
 'it was a really bad dream']

【讨论】:

    【解决方案2】:

    您可以使用filter() 方法并传递一个lambda,该lambda 将为没有"the" 作为倒数第二个字的字符串返回true:

    x = ['Mary had a little lamb', 
               'Jack went up the hill', 
               'Jill followed suit',    
               'i woke up suddenly',
               'I just missed the train',
               'it was a really bad dream']
    
    res = list(filter(lambda str : str.split()[-2] != "the", x)) 
    print(res) # ['Mary had a little lamb', 'Jill followed suit', 'i woke up suddenly', 'it was a really bad dream']
    

    【讨论】:

      【解决方案3】:
      x = ['Mary had a little lamb', 
                 'Jack went up the hill', 
                 'Jill followed suit',    
                 'i woke up suddenly',
                 'I just missed the train',
                 'it was a really bad dream']
      
      result = [y for y in x if y.split()[-2].lower() != 'the']
      
      print(result)
      # ['Jack went up the hill', 'I just missed the train']
      

      【讨论】:

        【解决方案4】:
        x = ['Mary had a little lamb', 
                   'Jack went up the hill', 
                   'Jill followed suit',    
                   'i woke up suddenly',
                   'I just missed the train',
                   'it was a really bad dream']
        
        res =[sentence for sentence in x if 'the'!= sentence.split()[-2]]
        
        print(res)
        

        输出

        ['Mary had a little lamb', 'Jill followed suit', 'i woke up suddenly', 'it was a really bad dream']
        

        【讨论】:

        • 如果'the'不是倒数第二个?
        猜你喜欢
        • 2021-10-24
        • 2016-10-25
        • 1970-01-01
        • 2019-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-15
        • 1970-01-01
        相关资源
        最近更新 更多