首页 > 解决方案 > 检查列表中是否包含某些内容

问题描述

我目前正在 CLI 中制作“火柴棒”游戏,它是 Player vs AI。几乎所有东西都正常工作,只是“AI”选择了一根之前被移除的棍子。

这是代码:

class CPyramide(object):
    def __init__(self, lines):
        self.pir = []
        for i in range(lines):
            sticks = ["|" for j in range(i+1)]
            self.pir.append(sticks)
    def __str__(self):
        o = ""
        for i, L in enumerate(self.pir):
            spaces = (len(self.pir) - i) * " "
            o += spaces
            o += " ".join(L)
            o += "\n"
        return o

    def stickDelete(self, line, n):
        self.pir[line] = self.pir[line][n:]

try:
    lines = int(sys.argv[1])
    sticks = int(sys.argv[2])
    cpir = CPyramide(lines)
    print(cpir)
    while True:
        print("Your turn:")
        inputLine = input("Line: ")
        inputSticks = input("Matches: ")
        if int(inputSticks) > sticks:
            print("Error: you cannot remove more than",sticks,"matches per turn")
            continue
        else:
            print("Player removed",inputSticks,"match(es) from line",inputLine)
            cpir.stickDelete(int(inputLine) - 1,int(inputSticks))
            print(cpir)
            print("AI's turn...")
            aiSticks = randint(1,sticks)
            aiLines = randint(1,lines)
            print("AI removed",aiSticks,"match(es) from line",aiLines)
            cpir.stickDelete(aiLines - 1,aiSticks)
            print(cpir)

我一直在尝试制作它,因此它会检查每个包含 [|] 的数组并可能将其删除,但我不知道如何制作它。

有没有办法让函数 cpir.stickDelete 检查数组中是否有 [|] 并可能随机删除它?因为每次我玩 AI 时,它都会选择之前已经被移除的东西。

有没有办法检查每个数组并可能检查它是否包含 [|] 并随机删除它?

谢谢阅读。

标签: pythonpython-3.x

解决方案


尝试这个 :

if "|" in my_list:
    my_list.remove("|")

推荐阅读