Python:将列表转换为普通值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2152401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:54:35  来源:igfitidea点击:

Python: Convert a list into a normal value

python

提问by Bruce

I have a list

我有一个清单

a = [3]
print a
[3]

I want ot convert it into a normal integer

我想把它转换成一个普通的整数

print a
3

How do I do that?

我怎么做?

回答by YOU

a = a[0]
print a
3

Or are you looking for sum?

或者你在找sum什么?

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

回答by Alok Singhal

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

问题不清楚。如果a只有一个元素,您可以通过以下方式获取:

a = a[0]

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

如果它有多个,那么您需要指定如何从多个中获取一个数字。

回答by brianray

I imagine there are many ways.

我想有很多方法。

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

如果你想要一个 int() 你应该把它投射到列表中的每个项目上:

>>> 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.

这也将清空 a 和 pop() 每个后处理情况,其中它们是字符串。

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

回答by Jesper Joachim S?rensen

To unpack a list you can use '*':

要解压缩列表,您可以使用“*”:

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

>>> print(*a)

1 4 f