【问题标题】:How to comma separate an array of integers in python? [closed]如何用逗号分隔python中的整数数组? [关闭]
【发布时间】:2019-09-26 09:32:23
【问题描述】:

我有一个整数列表,我想将它们转换为逗号分隔的整数,我该如何实现呢

结果应该是逗号分隔的整数,而不是逗号分隔的字符串 例子

def evaluate(self, list_of_integers):
   print(list_of_integers) # [220.0, 112.9] 
   # i want to achieve something like below
   print(comma_separated_integers) # 220.0, 112.9

【问题讨论】:

  • 试试:comma_separated_integers = ','.join(map(str, list_of_integers))
  • 如果你想更 Pythonic,甚至可以做一个生成器表达式而不是 map 像这样:",".join((str(i) for i in list_of_integers))
  • 不,它应该是一个整数,当我这样做时,它将逗号分隔值转换为字符串
  • 好吧 - printing 无论如何都需要字符串 - 它只是被转换的 output - 如果你这样做 print(','.join(map(str, list_of_integers))) 而不是你的列表本身跨度>

标签: python arrays python-3.x


【解决方案1】:

假设您有list 个数字:

numbers = [220.0, 112.9]

而您只想打印:

220.0, 112.9

你可以这样做:

print(*numbers,sep=', ') # prints 220.0, 112.9

星号运算符(也称为解包运算符)表示列表中的元素将用作后续参数。 sep=', ' 表示打印的元素将由, 后跟空格分隔。

【讨论】:

    【解决方案2】:

    您可以将它们转换为字符串,然后使用str.join

    integers = [106, 386, 53]
    
    ', '.join(map(str, integers))
    

    输出:

    '106, 386, 53'
    

    【讨论】:

    • 不,它应该是一个整数,当我这样做时,它将逗号分隔值转换为字符串
    • “逗号分隔整数”的概念没有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 2020-03-17
    相关资源
    最近更新 更多