Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

python - Checking if a list contains a certain sequence of numbers

I have a list of 5 ints from 1 to 6 (simulating 5 dice rolling), randomly generated for example:

L = [1,2,3,4,5]

and I want to check that if this list when sorted, contains either

[1,2,3,4] or [2,3,4,5] or [3,4,5,6].

How would I go about checking if list L contains any of the 3 combinations? I don't want to have to go through and check if

L[i] == l1 [i],  L[i]== l2 [i],  L[i]== l3 [i]

for int in the list. I feel like its just a simple question of asking if the list contains either of the other lists or something. I'm just having trouble connecting the dots and its not clicking for me. Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The in operator is handy for seeing if a sequence contains a single item, but it doesn't work to check for a list of items. However, it does work on strings, so just convert everything to a string.

s = ''.join(str(i) for i in sorted(L))
if '1234' in s or '2345' in s or '3456' in s:
    # ...

If you had many more conditions to check for you could simplify a little:

if any(sublist in s for sublist in ('1234', '2345', '3456')):

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...