这应该很简单。我想列出1到50之间可被3分割的所有数字:
a = [i for i in range(1,51) ]
[i for i in a % 3 == 0]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-50-42b9611b86db> in <module>()
----> 1 [i for i in a % 3 == 0]
TypeError: unsupported operand type(s) for %: 'list' and 'int'
为什么我会收到这个TypeError?
答案 0 :(得分:2)
正如您可能想要的评论中所述:
>>> [i for i in range(1, 51) if i % 3 == 0] # included an "if"
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]
另外,您可以直接从修改后的range
:
>>> [3 * i for i in range(1, 51 // 3)]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]
>>> list(range(3, 51, 3))
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]
在您的情况下,您获得TypeError
,因为您使用a % 3
而a
是list
,不支持除法或模运算。