2017-01-23 53 views
-3

我对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 

谢谢

+2

你有一个字符串列表。用'''.join(data)'将它转换为一个字符串。 – DyZ

+0

'n_zero'是一个str。你不能用列表多列加一个str。尝试'int(n_zero)' – Lucas

+1

print(''。join(map(str,data))) 我这样做,它的工作原理!谢谢! – jamarumori

回答

0

有2问题。这里是更正的代码,解释:

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

+2

他必须使用Python 2,否则他会从'* n_zero'中得到错误。所以他不需要调用int()。 – Barmar

0

刚过np.random.shuffle(data)线

添加一行代码它转换成列表字符串

data = ''.join(data) 

这会怎么做。

0

而不是创造数字列表的

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) 
0

如果这样

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, 

(注意逗号末)而不是您的打印声明。