我正在尝试编写一个接受宽度,高度和字符的代码。将其打印在网格中[W * H] 我的代码如下..
width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
c= raw_input("Initial char: ")
a=(width*c), (height*c)
print a
输出:
Width of myarray: 3
Height of Array: 3
Initial char: +
+++++++++
我需要[['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']]
这种格式的输出。
答案 0 :(得分:1)
width = 3
height = 3
c= '+'
row = []
a = []
# create an individual row with the given width
for i in range(0,width):
row.append(c)
# create the array of rows with the given height
for i in range(0,height):
a.append(row)
print a
输出:
[['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']]
没有for循环和范围的方法如下:
width = 3
height = 3
c= '+'
row = []
a = []
# create an individual row with the given width
row = [c] * width
# create the array of rows with the given height
a = [row] * height
print a
输出:
[['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']]
如果您想检查给定的值,则可以使用try / except块:
width = raw_input("Width of myarray: ")
height = raw_input("Height of Array: ")
c= raw_input("Initial char: ")
a = []
try:
width = int(width)
height = int(height)
row = []
row = [c] * width
a = [row] * height
print a
except:
print None
输出:
Width of myarray:
Height of Array:
Initial char:
None
答案 1 :(得分:0)
这应该有效。如果您愿意,可以在IDLE中逐行输入这些内容(Stack本身不支持Python的缩进要求):
def arr():
global array1
width = int(input('Enter width: \n'))
height = int(input('Enter height: \n'))
character = input('Desired character: \n')
array1 = [[character for i in range(width)] for i in range(height)]
print(array1)
使用以下方式调用:
arr()
它应该像这样运行:
>>> arr()
Enter width:
3
Enter height:
4
Desired character:
+
输出
[['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']]
修改强>
在回答下面的评论时,您可以使用:
def arr():
global array1
width = input('Enter width: \n')
if (width == ''):
print('None')
if (width.isnumeric()):
width1 = int(width)
height = input('Enter height: \n')
if (height == ''):
print('None')
if (height.isnumeric()):
height1 = int(height)
character = input('Desired character: \n')
if (character == ''):
print('None')
if (width != '' and height != '' and character != ''):
if (width.isnumeric() and height.isnumeric()):
array1 = [[character for i in range(width1)] for i in range(height1)]
print(array1)
else:
print('None')