[英]How to get rid of the use of “end” in loops(python) for only the last element?
By using end="-"
I got this loop.通过使用
end="-"
我得到了这个循环。 I want to remove that '-'
for the last element.我想删除最后一个元素
'-'
。
m=4
n=1
for i in range(1,4):
for x in range(5,n,-1):
print(" ",end="")
n+=2
for y in range(3,3-i,-1):
print(y,end="-")
for z in range(m,4):
print(z,end="-")
m-=1
print()
Output: Output:
3-
3-2-3-
3-2-1-2-3-
Instead of using end
, you can actually use sep
, which only separates between elements which sounds like what you want.除了使用
end
,您实际上可以使用sep
,它仅在听起来像您想要的元素之间进行分隔。 This will even reduce your loops a bit.这甚至会减少你的循环。
You will have to change the prints to be something like: print(*range(m, 4), sep='-')
.您必须将打印更改为:
print(*range(m, 4), sep='-')
。
The spaces ( ' '
) loop is also not necessary and can be a single print
, so your whole code can look like:空格(
' '
) 循环也不是必需的,可以是单个print
,因此您的整个代码可以如下所示:
m = 4
n = 1
for i in range(1, 4):
print(" " * abs(5-n), end='')
n += 2
print(*range(3, 3-i, -1), *range(m, 4), sep='-')
m -= 1
It is also possible to only use the loop variable i
and avoid maintaining m
and n
.也可以只使用循环变量
i
而避免维护m
和n
。 So the code can be reduced to:所以代码可以简化为:
m = 4
for i in range(1, m):
print(" " * abs(5-i*2+1), end='')
print(*range(3, 3-i, -1), *range(m-i+1, m), sep='-')
which gives:这使:
3
3-2-3
3-2-1-2-3
Finally, to make it more reasonable by m
being the range being printed, and making it completely generic to allow any m
you can do:最后,通过将
m
作为打印范围使其更合理,并使其完全通用以允许您可以执行任何m
:
m = 4
for i in range(1, m+1):
print(" " * (m*2-i*2), end='')
print(*range(m, m-i, -1), *range(m-i+2, m+1), sep='-')
Which will now print up-to 4
:现在最多可以打印
4
:
4
4-3-4
4-3-2-3-4
4-3-2-1-2-3-4
Welcome to SO!欢迎来到 SO!
Nice work progress, Here.工作进展顺利,来了。 in my solution I am trying to is to divide the responsibilities into smaller tasks.
在我的解决方案中,我试图将职责划分为更小的任务。
m=4
n=1
max_line_length = 20
def special_print(items):
# convert each number to string
str_items = [str(each) for each in items]
# prepare output string
output_string = '-'.join(str_items)
prefix = ' ' * (max_line_length - len(output_string))
print(prefix + output_string)
# try
# print(output_string.center(max_line_length))
for i in range(1,4):
items = []
n+=2
for y in range(3,3-i,-1):
items.append(y)
for z in range(m,4):
items.append(z)
m-=1
# print(items)
special_print(items)
Output Output
3
3-2-3
3-2-1-2-3
Note: This solution can be further simplified by Python Pros but I tried to keep simple enough for you to understand.注意:此解决方案可以通过 Python Pros 进一步简化,但我尽量保持简单,以便您理解。
You can explore python string objects features like center
, join
and list-comprehension, len function to improve your Python skills.您可以探索 python 字符串对象功能,如
center
、 join
和列表理解,len function 以提高您的 Python 技能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.