Python - 更优雅的解决方案?
Python - a more elegant solution?
这会产生所需的输出,但我可以看出这不是一个优雅的解决方案(重复三个类似的 for 循环)。这怎么能浓缩呢?能浓缩到什么程度才能使short/elegant成为尽可能的解决方案?提前致谢
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()
你可以这样做:
for item in range(1,16):
if item % 5 == 0:
print(item, "***", sep='')
continue
print(item, "***", sep='',end='')
它也returns相同的结果。
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'
这会产生所需的输出,但我可以看出这不是一个优雅的解决方案(重复三个类似的 for 循环)。这怎么能浓缩呢?能浓缩到什么程度才能使short/elegant成为尽可能的解决方案?提前致谢
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()
你可以这样做:
for item in range(1,16):
if item % 5 == 0:
print(item, "***", sep='')
continue
print(item, "***", sep='',end='')
它也returns相同的结果。
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'