I have a list of tuples which contains a string and another list. It is as follows:
board = [('10S', []), ('3H', []), ('6C', ['KS', '9C']), ('6H', []), ('7D', []), ('9S', ['AS', 'KS'])]
I want to traverse such that comparison is done as follows:
10S 3H
3H 6C
6C KS
6C 9C
6C 6H
6H 7D
and so on...
That is the get_mapping()
written below will call the values for prev2
and prev1
.
I have implemented the following code:
for val in board:
print "Val is: " + str(val)
if cnt == 0:
prev2 = val[0][0]
prev1 = val[1][0]
cnt += 1
get_mapping(prev2,prev1,True)
else:
prev2 = prev1
if len(val[1]) > 0:
for v in val[1]:
prev1 = v
cnt += 1
get_mapping(prev2,prev1,False)
else:
prev1 = val[0]
cnt += 1
get_mapping(prev2,prev1,True)
I know the first condition is wrong. I am stuck a little as to how to traverse to get above comparison. Any help will be appreciated.
You could write a generator yielding pairs:
Output:
In above
zip_longest
will yield items fromstate
as pairs. Since first parameter is longer than second one on last iterationNone
is used as fillvalue. Then the loop will firstyield from
generator that returns(key, list item)
tuples and finally yields current and next key.Update For Python 2 minor modifications are required since it doesn't have
yield from
andzip_longest
is known asizip_longest
: