簡體   English   中英

Python dict 與 int 條目比較與 int?

[英]Python dict with int entries comparison with int?

晚上好。 我試圖弄清楚如何將變量與字典中的 int 條目進行比較:我正在編寫街機游戲,我將 x 和 y 坐標存儲在 dict (xy) 和 playerx 和 playy 變量中,我想做一個比較,以便玩家是否達到字典中指定的坐標。 它會做些什么? 我怎么能 go 這樣做呢?

我想像這樣的事情:

if playerx in dict:
    if playery in dict[x]:
        dosomething()

但我無法完全弄清楚如何正確地做到這一點。

也許您可以使用元組列表

l_coord = [(1, 2), (2, 3), (4, 5)]
player_x = 2
player_y = 3
player = (player_x, player_y)
if player in l_coord:
    print("I am here.")

也許這就是你需要的:

player=(0,1)

your_dict = {0:1,1:2,2:3}

if player[0] in your_dict:
    if player[1] == your_dict[player[0]]:
        print("hello, is it me you're looking for?")

考慮到字典的速度,它的 python 數據結構非常快。 但如果您想真正直觀地可視化坐標,請嘗試創建一個空間(x,y)元組。 假設所有位置都由您的游戲方案正確管理。

#Code
d={"VillageLocation":(1,1)}
player1_location=(1,1)
player2_location=(2,2)
#check by values
reachedVillage = player1_location in d.values() #returns True #method for checking by values
if (reachedVillage == True):
    goToSleep("player1")

解釋:玩家 1 現在將 go 睡覺,因為玩家 1 的位置和村庄位置現在匹配,在“reachedVillage”變量中存儲為“真”。

使用的技巧:通過值而不是鍵檢查字典。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM