[英]Python Basics: How to convert a list containing an int into a plain int?
Why is this not giving me just "3" but still "[3]"? 为什么这不仅仅给我3,还给我[3]?
a = [3]
print "".join(str(a))
because you call the to string function on the entire list 因为您在整个列表上都调用了to字符串函数
try: 尝试:
a = [3]
print "".join([str(v) for v in a])
After reading the headline of the question are you just trying to get a single integer from a list, or do you want to convert a list of integer into a "larger" integer, eg: 阅读问题标题后,您只是想从列表中获取单个整数,还是要将整数列表转换为“更大”的整数,例如:
a = [3, 2]
print "".join([str(v) for v in a]) ## This gives a string and not integer
>>> "32"
You are taking str() on an array. 您正在数组上使用str()。 str convers [3] to "[3]".
str将[3]转换为“ [3]”。 You are probably looking for
您可能正在寻找
"".join(str(i) for i in a)
Perhaps just dereference by index: 也许只是通过索引取消引用:
print a[0]
Or: 要么:
for item in a:
print item
Because str(a)
gives you the string representation of a list, ie, "[3]". 因为
str(a)
为您提供了列表的字符串表示形式,即“ [3]”。
Try 尝试
"".join([str(elem) for elem in a])
to convert the list of ints to a list of strings before joining. 在加入之前将int列表转换为字符串列表。
这将产生预期的行为:
"".join([str(x) for x in a])
Pass in a generator expression to join rather then a list comprehension: 传递生成器表达式以加入,而不是列表理解:
"".join(str(x) for x in a)
If your list only contains numbers you might use repr() instead since thats what str() is going to do anyway: 如果您的列表仅包含数字,则可以改用repr(),因为那是str()要做的事情:
"".join(repr(x) for x in a)
If your using python 2.X you can use backticks as a shortcut for repr(). 如果您使用的是python 2.X,则可以使用反引号作为repr()的快捷方式。 But this isn't available in 3.X:
但这在3.X中不可用:
"".join(`x` for x in a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.