简体   繁体   English

python for 循环,带 2 个计数器

[英]python for-loop with 2 counters

I'd like to create a single for loop using 2 variables, instead of a for loop and an external variable.我想使用 2 个变量创建一个 for 循环,而不是一个 for 循环和一个外部变量。

Is there a way to do something unpacking tuples with range?有没有办法用范围解包元组?

Here is what I have:这是我所拥有的:

space = height
for h in range(height):
    # code using both h & space

Here is the code I'm trying to improve:这是我正在尝试改进的代码:

# Get positive integer between 1 - 8
while True:
    height = int(input("Height: "))
    if height > 0 and height < 9:
        break

space = height  # Control space count

# Build the pyramid
for h in range(height):
    print(" " * (space - 1),"#" * (h + 1), end="")
    print(" ", end="")
    print( "#" * (h + 1), " " * (space - 1), end="")
    space -= 1

    print()  # Get prompt on \n

You can use a second range object (from height to 0 ) and then zip to iterate both ranges at once:您可以使用第二个range object (从height0 )然后zip一次迭代两个范围:

# Get positive integer between 1 - 8
while True:
    height = int(input("Height: "))
    if height > 0 and height < 9:
        break

# Build the pyramid
for h, space in zip(range(height), range(height, 0, -1)):
    print(" " * (space - 1),"#" * (h + 1), end="")
    print(" ", end="")
    print( "#" * (h + 1), " " * (space - 1), end="")

    print()  # Get prompt on \n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM