python - 从 python 中的 JSON 文件创建纯 python 列表的更好方法
问题描述
我有一个JSON
文件在Python
. 文件内容如下。
{
"cities": [
"NY",
"SFO",
"LA",
"NJ"
],
"companies": [
"Apple",
"Samsung",
"Walmart"
],
"devices": [
"iphone",
"ipad",
"ipod",
"watch"
]
}
我想Python
从此JSON
文件创建列表。我已经完成了如下操作。
# Open JSON file in Python
with open('test.json') as out_file:
test_data = json.load(out_file)
# Query the output variable test_data
test_data
{u'cities': [u'NY', u'SFO', u'LA', u'NJ'], u'companies': [u'Apple', u'Samsung', u'Walmart'], u'devices': [u'iphone', u'ipad', u'ipod', u'watch']}
# find type of test_data
type(test_data)
<type 'dict'>
# create list from test_data
device = test_data['devices']
# Check content of list created
device
[u'iphone', u'ipad', u'ipod', u'watch']
现在你看到列表是一个unicode list
我希望它是一个纯粹的Python
列表。
我可以像下面那样做
device_list = [str(x) for x in device]
device_list
['iphone', 'ipad', 'ipod', 'watch']
有一个更好的方法吗?
解决方案
一种方法是使用map
前任:
l = [u'iphone', u'ipad', u'ipod', u'watch']
print(map(str, l))
蟒蛇3
print(list(map(str, l)))
输出:
['iphone', 'ipad', 'ipod', 'watch']
Unicode 或常规字符串没有太大区别
推荐阅读
- java - Rest DSL with Springboot on Camel 在重启 EAP 后创建路由抛出异常
- android - 无法扫描长条码
- html - 移动设备上的多选
- go - 我将如何在 golang 中为多种方法进行负载测试(vegeta)
- javascript - 无法从后台脚本接收选项卡上的消息
- java - java中的全局ArrayList中没有添加的值
- keystonejs - 两个模式 keystone.js 之间的未填充字段
- python - 注释多对多字段并返回查询集- Django
- python - 从 Spark 数据框中提取 Json 数据
- javascript - 您如何为 LinkedIn、Twitter 和 Facebook 等社交平台设置特色图片以拉入预览?