原文链接: http://www.juzicode.com/python-error-typeerror-unsupported-operand-types-for-or-pow/
错误提示:
对列表求幂提示TypeError: unsupported operand type(s) for ** or pow(): ‘list’ and ‘int’
#vx:桔子code / juzicode.com
a = [1,2,3,4,5,6,7]
x = a**2
print(x)
==========运行结果:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-4521911ae9fa> in <module>
1 #vx:桔子code / juzicode.com
2 a = [1,2,3,4,5,6,7]
----> 3 x = a**2
4 print(x)
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
错误原因:
1、列表不可以直接使用**运算符求幂
解决方法:
1、使用列表推导式计算
#vx:桔子code / juzicode.com
a = [1,2,3,4,5,6,7]
x = [t**2 for t in a]
print(x)
==========运行结果:
[1, 4, 9, 16, 25, 36, 49]
扩展内容:
如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。