The value between two list as shown below:
testlist = [1,3,5,7]
WinCombination = [ [7,5,3],[1,2,3],[3,5,7]]
I want to detect the value of [3,5,7] in WinCombination and it also exist in testArray = [1,3,5,7] with the same order. I cannot figure out the way to test between this list. I am beginner in Python. Thanks for helping
CodePudding user response:
whatever i understood from your question that you want to find a combination from testList in wincombination with same order..may be below code can help you.
wincombination=[[1,2,3],[2,3,4],[6,5,4]]
testArray=[1,2,3,4]
flag=False
for i in wincombination:
if i==testArray[1:]:
print("present")
flag=True
if flag==True:
print("not present")
CodePudding user response:
you should use itertools.combinations
to get the combinations from the lenght, convert WinCombinations
to a list
of tuples and check every time if the combination is in the list.
in this case i used list comprehension
in this case but you can also use the normal loop instead:
import itertools
testArray = [1,3,5,7]
WinCombination = [ [7,5,3],[1,2,3],[3,5,7]]
lentocheck=3
combined=[x for x in itertools.combinations(testArray,lentocheck) if x in list(map(tuple,WinCombination))]
print(combined)
output:
[(3, 5, 7)]
i had to convert WinCombinations
to a list of tuples because itertools.combinations
returns a list of tuples, in this way i can do the comparison.
CodePudding user response:
There is a simple way to get this done, it's just by comparing the str values of sequences.
str_test = str(testlist)[1:-1]
matches = [combination for combination in WinCombination
if str(combination)[1:-1] in str_test]
this will match every sub-array from testlist that is present in WinCombination by verifying if the string of testlist is a superset of combination string, the slicing [1:-1] is just to keep out brackets from string.