【发布时间】: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