简体   繁体   中英

converting list of string to list of integers in python

I have a dictionary like :

a={
   'sig2/Bit 2': ['0', '0', '1'], 
   'sig1/Bit 1': ['1', '0', '1']
  }

I want to convert it like :

a={
   'sig2/Bit 2': [0, 0, 1], 
   'sig1/Bit 1': [1, 0, 1]
  }

Please help me out.

I will not provide you with the complete answer but rather guidance on how to do it. Here is an example:

>>> d = ['0', '0', '1']
>>> print [int(i) for i in d]
[0,0,1]

Hopefully that should be enough to guide you to figure this out.
Hint: iterate through the dictionary and do this for each key/value pair. Good Luck

for i in a.keys():
    a[i] = [int(j) for j in a[i]]

May be there are better ways, but here is one.

for key in a:
    a[key] = [int(x) for x in a[key]];

Try this out

In [54]: dict([(k, [int(x) for x in v]) for k,v in a.items()])
Out[54]: {'sig1/Bit 1': [1, 0, 1], 'sig2/Bit 2': [0, 0, 1]}
for key, strNumbers in a.iteritems():
  a[key] = [int(n) for n in strNumbers]

You can try this ,

>>> a={
   'sig2/Bit 2': ['0', '0', '1'], 
   'sig1/Bit 1': ['1', '0', '1']
  }

>>> for i in a.keys():
        a[i]=map(int,a[i])

Output:

>>> print a
{'sig2/Bit 2': [0, 0, 1], 'sig1/Bit 1': [1, 0, 1]}

It is as easy as:

a = {
    'sig2/Bit 2': ['0', '0', '1'], 
    'sig1/Bit 1': ['1', '0', '1']
}

b = dict((x, map(int, y)) for x, y in a.iteritems())

UPDATE

For last line in code above you could use dict comprehension:

b = {x: map(int, y) for x, y in a.iteritems()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM