I am in the middle of writing a large piece of code and I want to shorten a length or
expression. Lets say we have a list, something like:
farm = ["cow","cow","cow", "hen","hen","hen", "fox","fox","fox", "hen","hen", "hen"]
lookfor = ["cow","hen"]
I am supposed to check whether there are three consecutive elements of lookfor
in farm
list.
One way is to do:
for i in range (0,len(farm) - 2):
if ((farm[i] == farm[i+1] == farm[i+2] == lookup[0])
or (farm[i] == farm[i+1] == farm[i+2] == lookup[1])):
//do something
Now if the number of elements in lookup
is small , it can written in the above way .However, if it is too long the code looks cumbersome and is harder to maintain. Is there a more concise way of writing the code , perhaps in list comprehension format - so that I do not have to manually write to look for all the elements of lookup
.
Aucun commentaire:
Enregistrer un commentaire