Easy way to convert a unicode list to a list conta

2019-01-31 03:35发布

Template of the list is:

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

I would like to convert from this

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

to this:

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

After conversion, I am actually checking if "1001" exists in EmployeeList.values().

8条回答
乱世女痞
2楼-- · 2019-01-31 03:38

You can do this by using json and ast modules as follows

>>> 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$']
查看更多
时光不老,我们不散
3楼-- · 2019-01-31 03:41

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
查看更多
仙女界的扛把子
4楼-- · 2019-01-31 03:45

Just simply use this code

EmployeeList = eval(EmployeeList)
EmployeeList = [str(x) for x in EmployeeList]
查看更多
混吃等死
5楼-- · 2019-01-31 03:47

There are several ways to do this. I converted like this

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

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

After that you can check

if '1001' in EmployeeList:
    #do something

Hope it will help you.

查看更多
\"骚年 ilove
6楼-- · 2019-01-31 03:54

We can use map function

print map(str, EmployeeList)
查看更多
戒情不戒烟
7楼-- · 2019-01-31 03:56

[str(x) for x in EmployeeList] would do a conversion, but it would fail if the unicode string characters do not lie in the ascii range.

>>> 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)
查看更多
登录 后发表回答