简体   繁体   English

查找字符串列表中的元素

[英]find elements for list in string

I have a string, 'RTKLOANGMSTTTS' and a list of tuples, [(2,5),(8,9)], that returns a string containing the letters 2-5 and 8-9 both inclusive, that is 'TKLOGM'. 我有一个字符串'RTKLOANGMSTTTS'和一个元组列表[[2,5),(8,9)],返回一个包含字母2-5和8-9(包括两个字母)的字符串,即'TKLOGM' 。 I was thinking something like: 我在想类似的东西:

def f(string, lst):
    for element in lst:
        if element in string:
            print string

But it does not return anything? 但是它不返回任何东西吗?

Try this: 尝试这个:

def f(source, lst):
    return "".join(source[start - 1:end] for start, end in lst)

What this will do is iterate over the lst , extracting the tuple into start and end on every iteration. 这将完成的遍历lst ,提取解析成startend在每个迭代上。 Then it will create a new string as a slice from the source string, from start - 1 to end (we use start - 1 because you showed that 1 means the first character, but python uses 0-indexing, so we must substract one). 然后它将从source字符串start - 1 (从start - 1end创建一个新的字符串作为切片(我们使用start - 1因为您显示1表示第一个字符,而python使用0索引,因此我们必须减去一个)。 。 Finally we join all the strings using "".join() . 最后,我们使用"".join()连接所有字符串。

If you use an older version of Python that doesn't support the generator syntax, use this instead: 如果您使用的旧版Python不支持生成器语法,请改用以下代码:

def f(source, lst):
    return "".join([source[start - 1:end] for start, end in lst])

It works exactly the same, but instead of working with a generator it explicitly creates a list which gets joined. 它的工作原理完全相同,但是没有使用生成器,而是显式创建了要加入的列表。

>>> x = 'RTKLOANGMSTTTS'
>>> l = [(2,5),(8,9)]
>>> ''.join(x[s-1:e] for (s,e) in l)
'TKLOGM'

I think this is what you asking for. 我想这就是你要的。 I can't test right now, but try: 我目前无法测试,但请尝试:

def f(string, lst):
    getStr = ''
    for t in lst:
        begin, end = t
        getStr += string[begin-1:end]
    return getStr
def f(string, lst):
   for start, end in lst:
       s = string[start-1:end]
       if s:
           yield s

for s in f('RTKLOANGMSTTTS', [(2,5),(8,9)]):
    print s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM