您好,我不知道从哪里开始或如何应对挑战,我是这种Python语言的新手。我想知道如何编写此代码。 “用户应该能够输入任何数字,例如,如果用户输入4个整数,则输出应为数组增量[1] [1 2] [1 2 3] [1 2 3 4],并且应为从最低到最大的三角形最高,输出中不应有“,”
rows = int(input('Type the number of rows: '))
for i in range (1, rows + 1):
print(list(range(1, i + 1)))
非常感谢你们。
答案 0 :(得分:2)
如果要使其具有三角形图案,则必须处理空格。
可以用很多方法来完成。这是一个:
n=int(input())
spaces=" "
for i in range(1,n+1):
spc=spaces*(n-1)
temp=[]
for j in range(1,i+1):
temp.append(str(j))
n-=1
print(spc+" ".join(temp))
For n=10 the pattern will look like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
如果您正在学习python,则可能会很难理解,但是您始终可以在互联网上搜索内容。
祝你好运!
答案 1 :(得分:0)
您当前的代码打印:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
我认为您想要的输出是
1
1 2
1 2 3
1 2 3 4
后者的代码是:
rows = int(input('Type the number of rows: '))
for i in range(1, rows+1):
print(' '.join(map(str, range(1, i+1))))
答案 2 :(得分:0)
只需使用join
,并记住添加括号
[1, 2, 3, 4]
和括号中删除逗号 x = ' '.join(map(str, [1, 2, 3, 4]))
print(x)
# 1 2 3 4
x = ' '.join(map(str, [1, 2, 3, 4]))
x = '['+x+']'
print(x)
#[1 2 3 4]
完整代码
for i in range(1, rows+1):
x = ' '.join(map(str, range(1, i+1)))
x = '['+x+']'
print(x)
#[1]
#[1 2]
#[1 2 3]
#[1 2 3 4]
答案 3 :(得分:0)
# numbers_list has the input()'ed' numbers
numbers_list = [1,2,7,4,6,5,3,8,10,9]
# sort the list
numbers_list = sorted(numbers_list)
total_numbers = len(numbers_list) + 1
# two output variants are attempted in the below code block(s)
"""
Variant #One
"""
# this will print the list with subscripts & comma sep
for index in range(1,total_numbers):
space_indent = " "*(total_numbers-index)
# this will allow the print not to rollover with newline.
print(space_indent,end=" ")
# use list slice to print
print(numbers_list[:index])
"""
Variant #Two
"""
# this will print the list withOUT subscripts & comma sep
for index in range(1,total_numbers):
space_indent = " "*(total_numbers-index)
print(space_indent,end=" ")
print(*numbers_list[:index])