这会产生所需的输出但是我可以看到它不是一个优雅的解决方案(重复三个类似的循环)。这怎么可以浓缩?它可以缩小到多远,使其成为尽可能短/优雅的解决方案?提前致谢
for planet in range(1): #this produces the rows (is this line needed?)
for column in range(1,6): #this produces the numbers
print(column, end="***")
print()
for column in range(6,11):
print(column,end="***")
print()
for column in range(11,15):
print(column,end="***")
print()
答案 0 :(得分:0)
你可以这样做:
for item in range(1,16):
if item % 5 == 0:
print(item, "***", sep='')
continue
print(item, "***", sep='',end='')
它也会返回相同的结果。
1***2***3***4***5***
6***7***8***9***10***
11***12***13***14***15***
您也可以在函数中替换变量以使其更具可读性,并且如果您需要修改行数和数量。列。
numColumns = 5
numValues = 15
for item in range(1,numValues+1):
if item % numColumns == 0: # If it is the last column in the row
print(item, "***", sep='') # Print the final column and a newline character (the default end character)
continue # Last column in row, skip the rest of the for loop and return to beginning
print(item, "***", sep='',end='') # Print the first few columns without a newline end character
# in the print() function:
# 'sep' is the separator between items in the print() function
# 'end' is the special character at the end of the print statement, which is by default the newline '\n'