Python 将整数列表转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26979266/
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
Convert a list of integers to string
提问by Mira Mira
I want to convert my list of integers into a string. Here is how I create the list of integers:
我想将我的整数列表转换为字符串。这是我创建整数列表的方法:
new = [0] * 6
for i in range(6):
new[i] = random.randint(0,10)
Like this:
像这样:
new == [1,2,3,4,5,6]
output == '123456'
采纳答案by jgritty
There's definitely a slicker way to do this, but here's a very straight forward way:
肯定有一种更巧妙的方法可以做到这一点,但这里有一个非常直接的方法:
mystring = ""
for digit in new:
mystring += str(digit)
回答by tynn
With Convert a list of characters into a stringyou can just do
使用Convert a list of characters into a string你可以做
''.join(map(str,new))
回答by jloup
Coming a bit late and somehow extending the question, but you could leverage the arraymodule and use:
来得有点晚,并以某种方式扩展了问题,但您可以利用该array模块并使用:
from array import array
array('B', new).tobytes()
b'\n\t\x05\x00\x06\x05'
In practice, it creates an array of 1-byte wide integers (argument 'B') from your list of integers. The array is then converted to a string as a binary data structure, so the output won't look as you expect (you can fix this point with decode()). Yet, it should be one of the fastest integer-to-string conversion methods and it should save some memory. See also documentation and related questions:
实际上,它会'B'从您的整数列表中创建一个 1 字节宽的整数数组(参数)。然后将数组转换为字符串作为二进制数据结构,因此输出不会像您预期的那样(您可以使用 修复这一点decode())。然而,它应该是最快的整数到字符串转换方法之一,它应该可以节省一些内存。另请参阅文档和相关问题:
https://www.python.org/doc/essays/list2str/
https://www.python.org/doc/essays/list2str/
https://docs.python.org/3/library/array.html#module-array
https://docs.python.org/3/library/array.html#module-array
回答by Cherry
You can loop through the integers in the list while converting to string type and appending to "string" variable.
您可以循环遍历列表中的整数,同时转换为字符串类型并附加到“字符串”变量。
for int in list:
string += str(int)
回答by Satyam Singh
two simple ways of doing this
两种简单的方法来做到这一点
"".join(map(str, A))
"".join([str(a) for a in A])

