将函数嵌套到函数中

时间:2019-03-04 19:35:45

标签: python function

我想长5英寸,创建了两个函数,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()

问题是我现在不知道如何将这两个函数结合在一起才能将它们都绘制在一个区域中。

1 个答案:

答案 0 :(得分:0)

与其具有两个分别打印输出的一部分的功能,不如具有一个单独的功能来打印整个输出的功能。您可以在全局范围内存储字符网格,以便可以通过用户输入将其写入并通过显示功能从中读取。

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的输出也可能掉入了黑洞。

相反,这就是 default stdout类似于文件的对象的行为。我们可以将打印到控制台的行为换成我们想要的任何东西。例如,内置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超出严格的必要范围,因此更新该行由您决定;-)

(**由于twins未定义,因此在fiveinches中将area更改为twins