我有這樣的元組串列:
rounds = [('R', 'S'), ('S', 'R'), ('S', 'R'), ('R', 'P'), ('S', 'S'),
('P', 'S'), ('P', 'S'), ('S', 'P'), ('R', 'R'), ('R', 'S')]
模擬 RPS 游戲的我也有這樣的功能:
def RPS_winner(weapon1, weapon2):
if weapon1 == weapon2:
return 0
elif (weapon1, weapon2) in [('R', 'S'), ('P', 'S'), ('P', 'S')]:
return 1
else:
return 2
我如何使用 map() 得出這 10 輪中的獲勝者名單?我知道是這樣開始的: list(map(RPS_winner, ....)
uj5u.com熱心網友回復:
Itertools 提供starmap了這一點。
from itertools import starmap
rounds = [('R', 'S'), ('S', 'R'), ('S', 'R'), ('R', 'P'), ('S', 'S'),
('P', 'S'), ('P', 'S'), ('S', 'P'), ('R', 'R'), ('R', 'S')]
def RPS_winner(weapon1, weapon2):
if weapon1 == weapon2:
return 0
elif (weapon1, weapon2) in [('R', 'S'), ('P', 'S'), ('P', 'S')]:
return 1
else:
return 2
list(starmap(RPS_winner, rounds))
# [1, 2, 2, 2, 0, 1, 1, 2, 0, 1]
uj5u.com熱心網友回復:
您不需要這樣map的東西,實際上可以通過使用串列理解來獲得可讀性:
>>> [RPS_winner(a, b) for a, b in rounds]
[1, 2, 2, 2, 0, 1, 1, 2, 0, 1]
另一種可能性是使用itertools.starmap,它是專門為此設計的:
from itertools import starmap
list(starmap(RPS_winner, rounds))
而且,當然,您可以手動執行相同的操作:
list(map(lambda ab: RPS_winner(*ab), rounds)
如果您打算在很長的 串列中使用rounds,那么重寫為:
def RPS_winner_star(ab):
return RPS_winner(*ab)
list(map(RPS_winner_star, rounds))
筆記
請求使用map或 之類的一個正當理由rounds實際上不是串列而是另一個迭代器。在這種情況下,很高興獲得一個新的迭代器,它rounds可以在不列出串列的情況下輸出獲勝者。例如,您可以將生成的迭代器“管道”到一個Counter:
irounds = generate_rounds(n=1_000_000) # a generator
iwinner = map(RPS_winner_star, irounds)
score_board = Counter(iwinner)
這是一個完整的例子:
import random
from collections import Counter
def generate_rounds(n):
for _ in range(n):
r = random.choice(list('RPS')), random.choice(list('RPS'))
yield r
%%time
irounds = generate_rounds(n=1_000_000) # a generator
iwinner = map(RPS_winner_star, irounds)
score_board = Counter(iwinner)
# CPU times: user 1.49 s, sys: 0 ns, total: 1.49 s
# Wall time: 1.49 s
%%time
rounds = list(generate_rounds(n=1_000_000))
winner = list(map(RPS_winner_star, rounds))
score_board = Counter(winner)
# CPU times: user 1.53 s, sys: 11.1 ms, total: 1.54 s
# Wall time: 1.54 s
%%time
rounds = list(generate_rounds(n=1_000_000))
winner = [RPS_winner(a, b) for a, b in rounds]
score_board = Counter(winner)
# CPU times: user 1.5 s, sys: 24.3 ms, total: 1.53 s
# Wall time: 1.53 s
如您所見,在此示例中,時序差異很小。
uj5u.com熱心網友回復:
你可以這樣做:
winners = list(map(lambda x: RPS_winner(*x), rounds))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398294.html
上一篇:Python中的質數
下一篇:如何連接多維串列元素內的字串?
