首页 > 解决方案 > 从 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']

有一个更好的方法吗?

标签: pythonjson

解决方案


一种方法是使用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 或常规字符串没有太大区别


推荐阅读