【问题标题】:Pythonic way of searching for a substring in a list在列表中搜索子字符串的 Pythonic 方式
【发布时间】:2010-11-18 15:47:18
【问题描述】:

我有一个字符串列表 - 类似于

mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text']

我想查找以 foobar 开头的任何内容的第一次出现。如果我是 grepping,那么我会搜索 foobar*。我目前的解决方案是这样的

for i in mytext:
    index = i.find("foobar")
    if(index!=-1):
        print i

哪个工作得很好,但我想知道是否有“更好”(即更 Pythonic)的方式来做到这一点?

干杯, 迈克

【问题讨论】:

  • 您的代码和您的 cmets 未对齐。 :) 你说你想要“任何以 foobar 开头的东西”(因此@THC4k 的答案),但是你的代码在任何地方打印所有包含“foobar”的字符串(因此其他人的答案)。
  • 同意 - 我在表达我的问题时不够小心。不过,我不会纠正它,以便后代可以看到我是愚蠢的人,而不是那些回答的人。对不起,谢谢大家的回答。

标签: string list python substring


【解决方案1】:

你也可以使用列表推导:

matches = [s for s in mytext if 'foobar' in s]

(如果您真的在寻找以 'foobar' 开头的字符串 ,正如 THC4k 所注意到的那样,请考虑以下事项:

matches = [s for s in mytext if s.startswith('foobar')]

【讨论】:

  • 现在我想知道作为生成器这样做是否更好:matches = (s for s in mytext if s.startswith('foobar')) 有人知道吗?
  • @Koen 如果 (a) 结果列表很大(尽管它只包含对原始字符串的引用),并且 (b) 你不需要结果是一件,例如做一个 len(matches) 或一个matches[-1],而是想要遍历它。
【解决方案2】:

如果您真的想要第一次出现以 foobar 开头的字符串(这就是您所说的,虽然与您的代码非常不同,但提供的所有答案,您提到的 grep ——您能得到多矛盾?-) ,试试:

found = next((s for s in mylist if s.startswith('foobar')), '')

如果 mylist 中没有项目满足条件,这将给出一个空字符串作为 found 结果。您也可以使用 itertools 等来代替简单的 genexp,但关键技巧是使用 next 默认内置函数(仅限 Python 2.6 和更好的版本)。

【讨论】:

  • +1 我只是在 (s for s in...)[0] 表达式上绞尽脑汁,只得到第一项,想知道如果没有第一项该怎么办...
  • @ThomasH,是的,在 2.5 中你必须做一个 try: / x=blah.next() / except StopIteration,2.6 的内置 next 更方便!
【解决方案3】:
for s in lst:
    if 'foobar' in s:
         print(s)

【讨论】:

    【解决方案4】:
    results = [ s for s in lst if 'foobar' in s]
    print(results)
    

    【讨论】:

      【解决方案5】:

      如果您真的在寻找 以 foobar 开头 的字符串(而不是 foobar in 它们):

      for s in mylist:
        if s.startswith( 'foobar' ):
           print s
      

      found = [ s for s in mylist if s.startswith('foobar') ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-03
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        • 2014-08-30
        • 2016-04-20
        相关资源
        最近更新 更多