簡體   English   中英

通過屬性在列表中查找對象

[英]Finding objects in a list by an attribute

我有以下代碼。 我正在嘗試創建對象列表,然后讓用戶輸入他們想查找的對象的名稱或屬性,以便他們可以在清單中找到該對象。 謝謝

import Game
import sys
import os
import time
import random

if __name__ == '__main__':
    pass

#constructor = name, ability, hitpoints, attack, gold, potions

def main():
    lst=[]
    c1 = Game.Character('j', "Forcefield", 100, 10, 0, 0)
    lst.append(c1)
    c2 = Game.Character("Sue", "Jump", 100, 10, 0, 0)
    lst.append(c2)

    x = input("Enter the name of the character to search for")

    for i in lst:
        if i == x:
            print("found")  


main()

您應該將輸入與實例的屬性進行比較。

for i in lst:
    if i.name == x:
        print("found")

迭代lst將在每次迭代中為您Game.Character i中的Game.Character對象。 代替i == x ,使用i.name == x

暫無
暫無

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

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