开发者

Python: Convert a list into a normal value

I have a list

a = [3]
print开发者_如何学Python a
[3]

I want ot convert it into a normal integer

print a
3

How do I do that?


a = a[0]
print a
3

Or are you looking for sum?

>>> a=[1]
>>> sum(a)
1
>>> a=[1,2,3]
>>> sum(a)
6


The problem is not clear. If a has only one element, you can get it by:

a = a[0]

If it has more than one, then you need to specify how to get a number from more than one.


I imagine there are many ways.

If you want an int() you should cast it on each item in the list:

>>> a = [3,2,'1']

>>> while a: print int(a.pop())

1
2
3

That would also empty a and pop() off each back handle cases where they are strings.

You could also keep a untouched and just iterate over the items:

>>> a = [3,2,'1']

>>> for item in a: print int(item)

3
2
1


To unpack a list you can use '*':

>>> a = [1, 4, 'f']

>>> print(*a)

1 4 f
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜