尝试在矩阵中创建偶数平方列表,出现错误

Trying to create a list of squares of even numbers in a matrix, getting error

这里是编码新手,正在尝试完成家庭作业:

下面给出一个二维矩阵,创建一个矩阵中所有偶数的平方列表。

这是我的代码:

myMatrix = [[1, 2, 'aa',3, 4],

        ['dd',5, 6, 7],

        [8, 9, 10,'cc']]
list=[i for row in myMatrix for i in row ]
V=[x**2 for x in list if x % 2 ==0]
V

我收到以下错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-95-6fae11330bf9> in <module>()
  5             [8, 9, 10,'cc']]
  6 list=[i for row in myMatrix for i in row ]
----> 7 V=[x**2 for x in list if x % 2 ==0]
  8 V

<ipython-input-95-6fae11330bf9> in <listcomp>(.0)
  5             [8, 9, 10,'cc']]
  6 list=[i for row in myMatrix for i in row ]
----> 7 V=[x**2 for x in list if x % 2 ==0]
  8 V

TypeError: not all arguments converted during string formatting

知道我哪里出错了吗?

您的矩阵还包含 str 值和 int。并且您不能对 str 对象执行 mod % 操作。如果你愿意,你会得到 TypeError。例如:

>>> 'aa' % 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

既然你的矩阵应该是 even 个数字的平方,你为什么还要使用 str 作为它的一部分?

试试这个:

new_list = []
for row in myMatrix:
    for x in row:
        if isinstance(x, int) and x % 2 == 0:
            new_list.append(x ** 2)

print new_list
# [4, 16, 36, 64, 100]

或通过列表理解:

new_list = [x**2 for row in myMatrix for x in row if instance(x, int) and x%2==0]

此外,您不应使用 list 作为变量名,因为它是保留数据类型。