34

列表模板为:

EmployeeList =  [u'<EmpId>', u'<Name>', u'<Doj>', u'<Salary>']

我想从这个转换

EmployeeList =  [u'1001', u'Karick', u'14-12-2020', u'1$']

对此:

EmployeeList =  ['1001', 'Karick', '14-12-2020', '1$']

转换后,我实际上是在检查 EmployeeList.values() 中是否存在“1001”。

4

9 回答 9

54

Encode each value in the list to a string:

[x.encode('UTF8') for x in EmployeeList]

You need to pick a valid encoding; don't use str() as that'll use the system default (for Python 2 that's ASCII) which will not encode all possible codepoints in a Unicode value.

UTF-8 is capable of encoding all of the Unicode standard, but any codepoint outside the ASCII range will lead to multiple bytes per character.

However, if all you want to do is test for a specific string, test for a unicode string and Python won't have to auto-encode all values when testing for that:

u'1001' in EmployeeList.values()
于 2013-08-16T11:18:54.183 回答
20

[str(x) for x in EmployeeList]会进行转换,但如果 unicode 字符串字符不在 ascii 范围内,它将失败。

>>> EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
['1001', 'Karick', '14-12-2020', '1$']


>>> EmployeeList = [u'1001', u'करिक', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
于 2013-08-16T11:17:21.657 回答
14

我们可以使用map函数

print map(str, EmployeeList)
于 2016-04-15T06:17:54.123 回答
7

只需简单地使用此代码

EmployeeList = eval(EmployeeList)
EmployeeList = [str(x) for x in EmployeeList]
于 2017-01-30T15:01:35.783 回答
5

how about:

def fix_unicode(data):
    if isinstance(data, unicode):
        return data.encode('utf-8')
    elif isinstance(data, dict):
        data = dict((fix_unicode(k), fix_unicode(data[k])) for k in data)
    elif isinstance(data, list):
        for i in xrange(0, len(data)):
            data[i] = fix_unicode(data[i])
    return data
于 2013-08-16T12:24:34.373 回答
1

只需使用

unicode_to_list = list(EmployeeList)
于 2018-01-04T11:07:29.513 回答
0

有几种方法可以做到这一点。我是这样转换的

def clean(s):
    s = s.replace("u'","")
    return re.sub("[\[\]\'\s]", '', s)

EmployeeList = [clean(i) for i in str(EmployeeList).split(',')]

之后你可以检查

if '1001' in EmployeeList:
    #do something

希望它会帮助你。

于 2018-10-04T08:54:38.160 回答
0

只是 json.dumps 将解决问题

json.dumps 函数实际上将所有 unicode 文字转换为字符串文字,我们可以轻松地将数据加载到 json 文件或 csv 文件中。

示例代码:

import json
EmployeeList =  [u'1001', u'Karick', u'14-12-2020', u'1$']
result_list = json.dumps(EmployeeList)
print result_list

输出:["1001", "Karick", "14-12-2020", "1$"]

于 2019-10-04T16:47:18.667 回答
0

您可以通过使用 json 和 ast 模块来执行此操作,如下所示

>>> import json, ast
>>>
>>> EmployeeList =  [u'1001', u'Karick', u'14-12-2020', u'1$']
>>>
>>> result_list = ast.literal_eval(json.dumps(EmployeeList))
>>> result_list
['1001', 'Karick', '14-12-2020', '1$']
于 2018-12-19T12:48:10.177 回答