hi
how to convert a = ['1', '2', '3', '4'] into a = [1, 2, 3, 开发者_开发知识库4] in one line in python ?With a list comprehension.
a[:] = [int(x) for x in a]
You can use map()
:
a = map(int, a)
This is an alternative to the (more common) list comprehension, that can be more succinct in some cases.
With a generator:
a[:] = (int(x) for x in a)
... list comprehensions are so ummmmm, 2.1, don't you know?
but please be wary of replacing the contents in situ; compare this:
>>> a = b = ['1', '2', '3', '4']
>>> a[:] = [int(x) for x in a]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
with this:
>>> a = b = ['1', '2', '3', '4']
>>> a = [int(x) for x in a]
>>> a
[1, 2, 3, 4]
>>> b
['1', '2', '3', '4']
l = []
a = ['1', '2', '3', '4']
l = [(int(x)) for x in a]
print l
[1, 2, 3, 4]
精彩评论