我有一个包含多米诺骨牌的列表(也是两个整数的列表),我需要找到其中一个多米诺骨牌的索引。
示例:
list_of_hand = [[[2, 5], [5, 5], [6, 5], [6, 4]], [[3, 2], [4, 5], [4, 4], [6, 1]]]这个列表是两个列表,包括玩家手中的所有多米诺骨牌。
如何找到domino [6, 5]的索引?
发布于 2018-03-27 14:23:08
您可以使用一个简单的函数搜索子列表:
x = [[[2, 5], [5, 5], [6, 5], [6, 4]], [[3, 2], [4, 5], [4, 4], [6, 1]]]
def hand_search(L, domino):
for s in L:
if domino in s:
return (L.index(s), s.index(domino))
return -1
print(hand_search(x, [6,5]))
print(hand_search(x, [6,1]))输出:
(0, 2) # 0 is the player, 2 is the position in their hand
(1, 3) # 1 is the player, 3 is the position in their hand只要嵌套是相同的,这就可以扩展到任意多的玩家。
发布于 2018-03-27 14:27:51
一种方法是在这样的循环中使用enumerate(PEP 279)函数:
def search(l,domino):
for m,i in enumerate(l):
for n,j in enumerate(i):
if domino == j:
return(m,n)
return("No match.")
>>> search(list_of_hand,[6,5])
(0, 2)发布于 2018-03-27 15:37:46
或者,您可以将所有内容保存在字典中:
dominos, hands = {}, {}
def give(d, h):
hands.setdefault(h, []).append(d)
dominos.update({d:h})
give( (6,5), 1 )
give( (2,5), 1 )
give( (3,2), 2 )
give( (5,5), 2 )
print hands # {1: [(6, 5), (2, 5)], 2: [(3, 2), (5, 5)]}
print dominos # {(2, 5): 1, (3, 2): 2, (6, 5): 1, (5, 5): 2}
print hands[2] # [(3, 2), (5, 5)]
print dominos[(6,5)] # 1https://stackoverflow.com/questions/49515359
复制相似问题