首页 > python > python:从列表中提取符号并消除unicode

python:从列表中提取符号并消除unicode (python: extract symbol from list and eliminate unicode)

问题

我想为符号创建列表,如下所示:

output = ['A','AA','AABA'...'ZYNE']

目前的输出是

[
    {u'name': u'Agilent Technologies Inc.', 
     u'symbol': u'A',
     u'iexId': u'2',
     u'date': u'2018-02-12',
     u'type': u'cs',
     u'isEnabled': True},
    {u'name': u'Alcoa Corporation',
     u'symbol': u'AA',
     u'iexId': u'12042',
     u'date': u'2018-02-12',
     u'type': u'cs',
     u'isEnabled': True},
    {u'name': u'Altaba Inc.',
     u'symbol': u'AABA', 
     u'iexId': u'7653',
     u'date': u'2018-02-12',
     u'type': u'cs',
     u'isEnabled': True},

我想消除unicode,只是从当前列表中提取符号。

我的代码如下

import urllib, json
url = "https://api.iextrading.com/1.0/ref-data/symbols"
response = urllib.urlopen(url)
data = json.loads(response.read())

我只设法得到一个输出data[0]["symbol"]'u'A'但不是在我想要的完整列表中

解决方法

只需使用:

output = [item['symbol'] for item in data]

编辑:

如果您知道所有'symbol'值都将使用ASCII,请使用:

output = [str(item['symbol']) for item in data]

除此以外:

[item['symbol'].encode('ascii', 'ignore') for item in data]

问题

I want to create list for symbols as below:

output = ['A','AA','AABA'...'ZYNE']

The current output is

[
    {u'name': u'Agilent Technologies Inc.', 
     u'symbol': u'A',
     u'iexId': u'2',
     u'date': u'2018-02-12',
     u'type': u'cs',
     u'isEnabled': True},
    {u'name': u'Alcoa Corporation',
     u'symbol': u'AA',
     u'iexId': u'12042',
     u'date': u'2018-02-12',
     u'type': u'cs',
     u'isEnabled': True},
    {u'name': u'Altaba Inc.',
     u'symbol': u'AABA', 
     u'iexId': u'7653',
     u'date': u'2018-02-12',
     u'type': u'cs',
     u'isEnabled': True},

I want to eliminate the unicode and just extract symbols out from the current list.

My code is as below

import urllib, json
url = "https://api.iextrading.com/1.0/ref-data/symbols"
response = urllib.urlopen(url)
data = json.loads(response.read())

I only manage to get one output as data[0]["symbol"] which returns 'u'A' but not in a complete list I want

解决方法

Just use:

output = [item['symbol'] for item in data]

EDIT:

If you know that all the 'symbol' values will be in ASCII just use:

output = [str(item['symbol']) for item in data]

Otherwise:

[item['symbol'].encode('ascii', 'ignore') for item in data]
相似信息