简体   繁体   English

输出不是我想要的

[英]The output is not as I want

I'm very new to python.我对python很陌生。 I am writing code to generate an array of number but the output is not as I want.我正在编写代码来生成一个数字数组,但输出不是我想要的。

The code is as follows代码如下

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)

The output is as follows :输出如下:

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]

I want the following output:我想要以下输出:

0031032030202110000

Thank you谢谢

There are 2 problems.有2个问题。 Here is the corrected code, the explanation:这是更正后的代码,解释如下:

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)

First, you need to convert the input from a string to an integer.首先,您需要将输入从字符串转换为整数。 I added int() in every input line.我在每个输入行中添加了int()

Then you have to convert the list you got, data to a string for the representation you want.然后你必须将你得到的列表, data转换为你想要的表示形式的字符串。 I did it with我做到了

s = ''.join(map(str, data))

because I like to use map when it makes the code concise.因为我喜欢用 map 来让代码简洁。 You can use a list comprehension if you like.如果您愿意,可以使用列表理解。

And eventually, print 's', of course, not data .最终,打印 's',当然不是data

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

add one more line of code which converts list into string再添加一行代码,将列表转换为字符串

data = ''.join(data)

This would do.这样就可以了。

Instead of creating a list of numbers而不是创建数字列表

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

create a list of characters创建字符列表

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

and then instead of然后代替

    print(data)

use

    print "".join(data)

If the output like this如果输出是这样的

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

(with spaces between numbers) is acceptable for you, use (数字之间有空格)对您来说是可以接受的,请使用

for i in data: print i,

(note the comma at the end) instead of your printing statement. (注意末尾的逗号)而不是您的打印语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM