【问题标题】:Convert a list of integers to string将整数列表转换为字符串
【发布时间】:2015-01-14 18:04:24
【问题描述】:

我想将我的整数列表转换为字符串。以下是我创建整数列表的方法:

new = [0] * 6
for i in range(6):
    new[i] = random.randint(0,10)

像这样:

new == [1,2,3,4,5,6]
output == '123456'

【问题讨论】:

  • new = [ random.randint(0,10) for i in range(6) ] 会更简单。

标签: python string list int


【解决方案1】:

有了Convert a list of characters into a string,你就可以做到

''.join(map(str,new))

【讨论】:

  • 或者对于map-averse,''.join([str(x) for x in new])
  • 甚至''.join(str(random.randint(0, 10)) for i in range(10))
【解决方案2】:

肯定有一种更巧妙的方法可以做到这一点,但这里有一个非常直接的方法:

mystring = ""

for digit in new:
    mystring += str(digit)

【讨论】:

    【解决方案3】:

    两种简单的方法

    "".join(map(str, A))
    "".join([str(a) for a in A])
    

    【讨论】:

      【解决方案4】:

      有点晚了,并以某种方式扩展了问题,但您可以利用 array 模块并使用:

      from array import array
      
      array('B', new).tobytes()
      
      b'\n\t\x05\x00\x06\x05'
      

      实际上,它会从您的整数列表中创建一个 1 字节宽的整数数组(参数 'B')。然后该数组被转换为二进制数据结构的字符串,因此输出看起来不像您期望的那样(您可以使用decode() 修复这一点)。然而,它应该是最快的整数到字符串转换方法之一,它应该可以节省一些内存。另请参阅文档和相关问题:

      https://www.python.org/doc/essays/list2str/

      https://docs.python.org/3/library/array.html#module-array

      Converting integer to string in Python?

      【讨论】:

      • 也许只有 python 3?在 python 2 中我无法使用 tobytes。
      【解决方案5】:

      如果你不喜欢map():

      new = [1, 2, 3, 4, 5, 6]
      
      output = "".join(str(i) for i in new)
      # '123456'
      

      请记住,str.join() 接受 iterable,因此无需将参数转换为 list

      【讨论】:

        【解决方案6】:

        您可以在转换为字符串类型并附加到“字符串”变量时遍历列表中的整数。

        for int in list:
            string += str(int)
        

        【讨论】:

        • 完全不同
        • 有什么办法,能不能帮帮我。
        • @Cherry 你的代码完全一样,改变量名不会让代码不一样
        • 另外,这是非常糟糕的做法。永远不要使用保留名称作为变量名。
        • @WhatsThePoint 不一样,只是你看不到
        猜你喜欢
        • 1970-01-01
        • 2021-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-03
        • 2012-05-08
        • 1970-01-01
        相关资源
        最近更新 更多