Python3,可分为三个,typeError

时间:2017-06-02 10:43:36

标签: python python-3.x typeerror

这应该很简单。我想列出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?

1 个答案:

答案 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 % 3alist,不支持除法或模运算。