首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >检索数组中每个项的元素

检索数组中每个项的元素
EN

Stack Overflow用户
提问于 2018-05-31 05:05:13
回答 2查看 41关注 0票数 1

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

代码语言:javascript
复制
[{"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}, ... ]

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

EN

回答 2

Stack Overflow用户

发布于 2018-05-31 05:36:31

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

代码语言:javascript
复制
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', ...] 
票数 2
EN

Stack Overflow用户

发布于 2018-05-31 06:05:26

如果您喜欢使用第三方库,pandas会直接接受字典列表:

代码语言:javascript
复制
import pandas as pd
from io import StringIO
import json

mystr = StringIO("""[{"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}]""")

# replace mystr with 'file.json'
df = pd.read_json(mystr)

# extract names to list
res = df['name'].tolist()

print(res)

['Bitcoin', 'Ethereum']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50613346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档