1

I have a list of strings like the following in 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.

I tried this but it was not working though, any advice? thx!

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

4 Answers 4

4

You could do this iteratively checking if the next character was a D and implementing some sort of counter. 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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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.

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.