我有一个元组列表,其中包含一个字符串和另一个列表.它如下:
board = [('10S', []), ('3H', []), ('6C', ['KS', '9C']), ('6H', []), ('7D', []), ('9S', ['AS', 'KS'])]
我想遍历这样的比较,如下所示:
10S 3H
3H 6C
6C KS
6C 9C
6C 6H
6H 7D
等等…
也就是说,下面写的get_mapping()将调用prev2和prev1的值.
我已经实现了以下代码:
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)
我知道第一个条件是错误的.关于如何遍历以进行比较,我有点困惑.任何帮助将不胜感激.
你可以编写一个生成对的生成器:
from itertools import zip_longest
master_board_state = [('10S', []), ('3H', []), ('6C', ['KS', '9C']),
('6H', []), ('7D', []), ('9S', ['AS', 'KS'])]
def pairs(state):
for (key, lst), nxt in zip_longest(state, state[1:]):
yield from ((key, x) for x in lst)
if nxt is not None:
yield key, nxt[0]
print('\n'.join(str(p) for p in pairs(master_board_state)))
输出:
('10S', '3H')
('3H', '6C')
('6C', 'KS')
('6C', '9C')
('6C', '6H')
('6H', '7D')
('7D', '9S')
('9S', 'AS')
('9S', 'KS')
在zip_longest以上将从州生产物品.由于第一个参数在最后一次迭代时长于第二个参数,因此无用作fillvalue.然后循环将首先从返回(key,list item)元组的生成器产生,最后产生当前和下一个键.
更新对于Python 2,需要进行微小的修改,因为它没有产生的收益,而zip_longest被称为izip_longest:
from itertools import izip_longest
master_board_state = [('10S', []), ('3H', []), ('6C', ['KS', '9C']),
('6H', []), ('7D', []), ('9S', ['AS', 'KS'])]
def pairs(state):
for (key, lst), nxt in izip_longest(state, state[1:]):
for x in lst:
yield key, x
if nxt is not None:
yield key, nxt[0]
print '\n'.join(str(p) for p in pairs(master_board_state))