在返回语句中使用for循环

0 投票
3 回答
1537 浏览
提问于 2025-04-18 12:27

我在这段代码上遇到了问题:

List=[' ', 'X', 'X', 'X']+[' ']*6
le='X'
def Return():
    return((for i in range(1, 10, 3):
        (List[i]==le and List[i+1]==le and List[i+2]==le)))

我想用一个for循环来写,而不是像这样指定:

 def Return():
    return ((List[1]==le and List[2]==le and List[3]==le) or #True
        (List[4]==le and List[5]==le)...etc.)

但是当我使用for循环的时候,系统只给我一个“语法错误”的提示,我不知道为什么会这样。

3 个回答

1

你可以试试用 any 这个东西。

lis=[' ', 'X', 'X', 'X']+[' ']*6
le='X'
def func():
    return any(all(lis[j]==le for j in range(i,i+3)) for i in range(0,len(lis),3)

注意:千万不要把 Python 的关键字当作方法名和变量名。

1

这是因为在Python中,for 不是一个表达式,它没有可以用来 return 的值。

2

你可以使用一种叫做 “列表推导式” 的东西:

def Return():
    return any([List[i]==le and List[i+1]==le and List[i+2]==le for i in range(1, 10, 3)])

撰写回答