简体   繁体   English

如果 var 等于 object 名称 - Z23EEEB4347BDD26BFC6B7EE9A3B755DD,则在 json 文件中获取 object 的值

[英]Get value of object in json file if var is equal to object name - python

I have a function that sees what card is in a player's hand and will add to their score depending on the card in their hand.我有一个 function 可以查看玩家手中的牌,并根据他们手中的牌增加他们的分数。 I have all the card values stored in a JSON file.我将所有卡值存储在 JSON 文件中。 I have code this so far:到目前为止我有这个代码:

with open("values.json") as values:
    value = json.load(values)
    for i in range(0, len(hand)):
        card = hand[i]

values.json值。json

{
    "3Hearts": 3
}

if the card is 3Hearts how could I get the 3 to be returned?如果卡是3Hearts ,我怎样才能让 3 被退回? Or is there a better way to store the data?还是有更好的方法来存储数据?

I will admit I am not very familiar with json files.我承认我对 json 文件不是很熟悉。 However if the json file is not a necessity you could just store the data in another.py file (Cards.py for example).但是,如果 json 文件不是必需的,您可以将数据存储在 another.py 文件中(例如 Cards.py)。

Also, because you are using python, you would be better off making a Card class and make Card objects .此外,因为您使用的是 python,所以最好制作Card class并制作Card objects This is what it would look like:这就是它的样子:

    # Make Card Class
    class Card:
        def __init__(self, name, number):
            self.name = name
            self.number = number


    # Make Card Objects
    threehearts = Card("3Hearts", "3")

Here I used threehearts instead of 3Hearts because making an object name starting with a number is not good practice.这里我使用threehearts而不是3Hearts ,因为以数字开头的object 名称不是一个好习惯。 To compensate I made an attribute Card.name where you can "name" the card "3Hearts" as you did in the question.作为补偿,我创建了一个属性Card.name ,您可以在其中“命名”卡片"3Hearts" ,就像您在问题中所做的那样。

So assuming you are going to use that.py file to store your data, this is what I would propose:因此,假设您要使用 that.py 文件来存储数据,这就是我的建议:

    # Import data here
    from Cards import*

    # Make the player's hand
    hand = [threehearts]

    # Display the number corresponding to the player's hand
    for i in range(0, len(hand)):
        card = hand[i]
        print(card.number)

The output of this code will be:此代码的 output 将是:

    3

You can also store hand = [threehearts] in the Cards.py file as well if you need to.如果需要,您也可以将hand = [threehearts]存储在 Cards.py 文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM