简体   繁体   English

字符串列表中的Python搜索模式

[英]Python searching patterns in lists of strings

I have a list of strings like the following in Python: 我在Python中有一个类似于以下字符串的列表:

         SS = ['T', 'Q', 'T', 'D', 'Q', 'D', 'D', 'Q', 'T', 'D']

Is there anyway I could check how many Ts are directly followed by D, so in this case, there are 2 Ts (second and the last T) that meet the requirement. 无论如何,我可以检查D后面紧跟多少T,因此在这种情况下,有2个T(第二个和最后一个T)可以满足要求。

I tried this but it was not working though, any advice? 我试过了,但是还是没用,有什么建议吗? thx! 谢谢!

            if ['T','Q'] in SS:
                 print ("yes")

You could do this iteratively checking if the next character was a D and implementing some sort of counter. 您可以迭代地检查下一个字符是否为D并实现某种计数器。 This is (probably) the tersest, although maybe not the best way. 这(可能)是最有趣的,尽管可能不是最好的方法。

SS = ['T', 'Q', 'T', 'D', 'Q', 'D', 'D', 'Q', 'T', 'D']
print("".join(SS).count("TD"))

Result: 结果:

2
SS = ['T', 'Q', 'T', 'D', 'Q', 'D', 'D', 'Q', 'T', 'D']
print zip(SS, SS[1:]).count(('T', 'D'))

A sequence of single-character strings can be expressed either as your given list or as a multi-character string, the main differences being list methods vs str methods (there's also the tuple type), and mutability. 一串单字符字符串可以表示为给定list或多字符字符串,主要区别在于list方法与str方法(还有tuple类型)以及可变性。

>>> SS = ['T', 'Q', 'T', 'D', 'Q', 'D', 'D', 'Q', 'T', 'D']
>>> SS_joined = ''.join(SS)
>>> 'TQ' in SS_joined
True

You can always you re. 你永远可以。

>>> import re
>>> SS = ['T', 'Q', 'T', 'D', 'Q', 'D', 'D', 'Q', 'T', 'D']
>>> new = ''.join(SS)
>>> len(re.findall('TD',new))
2

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

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