【问题标题】:The output is not as I want输出不是我想要的
【发布时间】:2026-01-25 18:10:02
【问题描述】:

我对 python 很陌生。我正在编写代码来生成一个数字数组,但输出不是我想要的。

代码如下

import numpy as np

n_zero=input('Insert the amount of 0:  ')
n_one =input('Insert the amount of 1: ')
n_two =input('Insert the amount of 2: ')
n_three = input('Insert the amount of 3: ')

data = [0]*n_zero + [1]*n_one + [2]*n_two + [3]*n_three
np.random.shuffle(data)
print(data)

输出如下:

Insert the amount of 0:  10
Insert the amount of 1: 3
Insert the amount of 2: 3
Insert the amount of 3: 3
[0, 0, 3, 1, 0, 3, 2, 0, 3, 0, 2, 0, 2, 1, 1, 0, 0, 0, 0]

我想要以下输出:

0031032030202110000

谢谢

【问题讨论】:

  • 你得到了一个字符串列表。使用''.join(data) 将其转换为字符串。
  • n_zero 是一个字符串。您不能将 str 与列表相乘。试试int(n_zero)
  • print(''.join(map(str, data))) 我这样做了,它有效!谢谢!
  • @lbellomo 他必须使用 Python 2,所以 input() 评估输入。

标签: python python-2.7 output


【解决方案1】:

有两个问题。这是更正后的代码,解释:

import numpy as np

n_zero=int(input('Insert the amount of 0:  '))
n_one =int(input('Insert the amount of 1: '))
n_two =int(input('Insert the amount of 2: '))
n_three = int(input('Insert the amount of 3: '))

data = [0]*n_zero + [1]*n_one + [2]*n_two + [3]*n_three
np.random.shuffle(data)
s = ''.join(map(str, data))

print(s)

首先,您需要将输入从字符串转换为整数。我在每个输入行中添加了int()

然后你必须将你得到的列表 data 转换为你想要的表示形式的字符串。我用

做到了
s = ''.join(map(str, data))

因为我喜欢使用 map 来简化代码。如果您愿意,可以使用列表推导式。

最后,打印“s”,当然不是data

【讨论】:

  • 他必须使用 Python 2,否则他会收到来自*n_zero 的错误。所以他不需要打电话给int()
【解决方案2】:

就在np.random.shuffle(data) 行之后

再添加一行代码,将列表转换为字符串

data = ''.join(data)

这样就可以了。

【讨论】:

    【解决方案3】:

    而不是创建一个数字列表

        data = [0]*n_zero + [1]*n_one + [2]*n_two + [3]*n_three
    

    创建一个字符列表

        data = ["0"] * n_zero + ["1"] * n_one + ["2"] * n_two + ["3"] * n_three
    

    然后代替

        print(data)
    

    使用

        print "".join(data)
    

    【讨论】:

      【解决方案4】:

      如果这样的输出

      0 0 3 1 0 3 2 0 3 0 2 0 2 1 1 0 0 0 0
      

      (数字之间有空格)可以接受,请使用

      for i in data: print i,
      

      (注意末尾的 逗号)而不是您的打印语句。

      【讨论】:

        最近更新 更多