这产生了所需的输出,但我看到它不是一个优雅的解决方案(重复三个相似的循环)。这怎么能被浓缩?它能浓缩到多大程度才能使它尽可能的简短/优雅呢?提前感谢
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()发布于 2016-03-15 15:01:27
你可以这样做:
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'https://stackoverflow.com/questions/36014163
复制相似问题