首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python -更优雅的解决方案?

Python -更优雅的解决方案?
EN

Stack Overflow用户
提问于 2016-03-15 14:30:13
回答 1查看 44关注 0票数 0

这产生了所需的输出,但我看到它不是一个优雅的解决方案(重复三个相似的循环)。这怎么能被浓缩?它能浓缩到多大程度才能使它尽可能的简短/优雅呢?提前感谢

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-15 15:01:27

你可以这样做:

代码语言:javascript
复制
for item in range(1,16):
    if item % 5 == 0:
        print(item, "***", sep='')
        continue

    print(item, "***", sep='',end='')

它还返回相同的结果。

代码语言:javascript
复制
1***2***3***4***5***
6***7***8***9***10***
11***12***13***14***15***

您还可以替换函数中的变量,使其更易读,如果需要修改行数和列数。

代码语言:javascript
复制
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'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36014163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档