将函数嵌套到函数中

2024-09-30 16:28:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做五英寸,我创建了两个函数,axe()创建游戏数组的轴,area()根据指定的坐标插入“X”。你知道吗

fiveinches = []
def axe():
    for a in range(1, 10):
        x = []
        x.append(a)
        print("", a, end="")
    for b in range(1, 10):
        y = []
        if b == 1:
            y.append(b)
            print("\n", b, sep="")
        else:
            print(b)
def area():
    for i in range(1,10):
        temp = []
        for j in range(1,10):
            temp.append(" ")
        fiveinches.append(temp)

    fiveinches[n][m] = "X"
    for list in twins:
        for element in list:
            print(element, end="")
        print(end="\n")

print("there is a player with crosses")
n = int(input("Enter the coordinate X: "))
m = int(input("Enter the coordinate Y: "))

#axe() or area()

问题是,我现在不知道如何将这两个函数耦合起来,使它们都绘制在一个区域中。你知道吗


Tags: 函数infordefrangeareaelementtemp
1条回答
网友
1楼 · 发布于 2024-09-30 16:28:13

与其使用两个函数分别打印输出的一部分,不如使用一个函数打印整个输出。您可以在全局范围中存储一个字符网格,这样就可以由用户输入写入,并由display函数读取。你知道吗

grid = [[' ' for x in range(10)] for y in range(10)]
for i in range(1, 10):
    grid[0][i] = str(i)
    grid[i][0] = str(i)

def display_grid():
    for row in grid:
        print("".join(row))

while True:
    for char in "XO":
        x = int(input("Enter x Coordinate."))
        y = int(input("Enter y Coordinate."))
        grid[y][x] = char
        display_grid()

结果:

Enter x Coordinate.3
Enter y Coordinate.3
 123456789
1
2
3  X
4
5
6
7
8
9
Enter x Coordinate.4
Enter y Coordinate.7
 123456789
1
2
3  X
4
5
6
7   O
8
9

如果你必须完全保持你的功能不变,那么你将面临一场艰难的战斗。一旦将数据打印到控制台,Python就几乎无法访问或操作它。当area执行时,axe的输出也可能落入黑洞。你知道吗

相反,这就是defaultstdout类文件对象的行为方式。我们可以根据需要交换print to console行为;例如,内置的io.StringIO类可以静默地捕获axe()和area()的输出。然后我们可以把它们组合起来,打印成普通的标准输出。你知道吗

你几乎不想真的这么做。当数据无法以任何其他方式检索时,捕获标准输出是一种绝望的策略。您可以完全控制您的数据,因此您应该首先尝试其他十几种方法。但既然你问:

from contextlib import contextmanager
import io
import sys
import itertools

@contextmanager
def capture_stdout():
    old_stdout = sys.stdout
    try:
        sys.stdout = io.StringIO()
        yield sys.stdout
    finally:
        sys.stdout = old_stdout

def combine(a,b):
    """combines two multiline strings."""
    results = []
    for line_a, line_b in itertools.zip_longest(a.split("\n"), b.split("\n")):
        result_line = []
        for char_a, char_b in itertools.zip_longest(line_a or "", line_b or ""):
            result_line.append(next((c for c in (char_a, char_b) if c is not None and c != " "), " "))
        results.append("".join(result_line))
    return "\n".join(results)


fiveinches = []
def axe():
    for a in range(1, 10):
        x = []
        x.append(a)
        print("", a, end="")
    for b in range(1, 10):
        y = []
        if b == 1:
            y.append(b)
            print("\n", b, sep="")
        else:
            print(b)
def area():
    for i in range(1,10):
        temp = []
        for j in range(1,10):
            temp.append(" ")
        fiveinches.append(temp)

    fiveinches[n][m] = "X"
    for list in fiveinches:
        for element in list:
            print(element, end="")
        print(end="\n")

print("there is a player with crosses")
n = int(input("Enter the coordinate X: "))
m = int(input("Enter the coordinate Y: "))
with capture_stdout() as axe_output:
    axe()
with capture_stdout() as area_output:
    area()

print(combine(axe_output.getvalue(), area_output.getvalue()))

结果:

there is a player with crosses
Enter the coordinate X: 2
Enter the coordinate Y: 8
 1 2 3 4 5 6 7 8 9
1
2       X
3
4
5
6
7
8
9

我注意到X并没有完全与轴对齐-它不是与左边的8和上面的2对齐,而是与左边的2和上面的4.5对齐。也许您可以修改fiveinches[n][m] = "X",以便将字符放置在正确的位置。但是我答应过不会改变area超出严格必要的范围,所以更新这一行取决于您;-)

(*除了在area中将twins更改为fiveinches之外,因为twins未定义)

相关问题 更多 >