Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python “如何修复”;SyntaxError:生成器表达式必须用括号括起来;在我的代码里?_Python_Python 3.x_Python 3.7 - Fatal编程技术网

Python “如何修复”;SyntaxError:生成器表达式必须用括号括起来;在我的代码里?

Python “如何修复”;SyntaxError:生成器表达式必须用括号括起来;在我的代码里?,python,python-3.x,python-3.7,Python,Python 3.x,Python 3.7,我想写一个程序,用一个数字作为输入求平方和。如果我给代码加5,它应该返回(0^2+1^2+2^2+3^2+4^2+5^2=55) 但我有一个这样的错误 sum(list(map(lambda x:i**2 for i in range(x+1),55))) ^ SyntaxError: Generator expression must be parenthesized 您不需要使用map sum(i**2 for i in range(x + 1)) 就像Guy提到

我想写一个程序,用一个数字作为输入求平方和。如果我给代码加5,它应该返回(0^2+1^2+2^2+3^2+4^2+5^2=55)

但我有一个这样的错误

sum(list(map(lambda x:i**2 for i in range(x+1),55)))
            ^
SyntaxError: Generator expression must be parenthesized

您不需要使用
map

sum(i**2 for i in range(x + 1))

就像Guy提到的那个样,若你们只是在累积和之后,那个么下面的代码块就足够了

sum(i**2 for i in range(x+1))
map
函数从传入的表达式/迭代器返回迭代器。比如说,如果你想在0..5的数字平方上进行迭代,那么下面将返回0,1,4,9,16,并且可以使用
for loop

    result_iterator= map(lambda x: x**2, range(5))
    for i in result_iterator:
        print(i)

我不知道你为什么不把它括起来。但是,即使您这样做了,您也会得到另一个错误,因为您不能迭代整数5。我不知道这个代码应该如何工作。
    result_iterator= map(lambda x: x**2, range(5))
    for i in result_iterator:
        print(i)