gpt4 book ai didi

python - 检索数组中每个项目的元素

转载 作者:行者123 更新时间:2023-11-30 22:14:05 24 4
gpt4 key购买 nike

这是我正在使用的文本文件的内容:

[{"name": "Bitcoin", "symbol": "BTC", "rank": 1, "slug": "bitcoin", "tokens": ["Bitcoin", "bitcoin", "BTC"], "id": 1},
{"name": "Ethereum", "symbol": "ETH", "rank": 2, "slug": "ethereum", "tokens": ["Ethereum", "ethereum", "ETH"], "id": 1027}, ... ]

如何检索每个硬币的每个“名称”元素并将其保存到临时变量中?

最佳答案

这看起来像一个有效的 JSON ,所以只需使用内置的 json解析它的模块,例如:

import json

with open("path/to/your_file.txt", "r") as f: # open the file for reading
data = json.load(f) # parse it as JSON

# now you can access the data hierarchically, i.e.
print("The first coin is {} and its symbol is {}".format(data[0]["name"], data[0]["symbol"]))
# The first coin is Bitcoin and its symbol is BTC

# or if you want just a list of all names
coin_names = [d["name"] for d in data] # ['Bitcoin', 'Ethereum', ...]

关于python - 检索数组中每个项目的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50613346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com