我有一个列表 r和一个列表 l
r = get_r()
l = [['a', 'b'], ['a'], ['c']]
print('-')
[print(type(el)) for el in l];
print('-')
[print(type(el)) for el in r];
会给我们
-
<class 'list'>
<class 'list'>
<class 'list'>
-
<class 'list'>
<class 'list'>
<class 'list'>
所以让我们打印r和 l
print(l)
print(r)
会给我们
[['a', 'b'], ['a'], ['c']]
[['Schadenersatzrecht'], ['Abgabenrecht, Finanzrecht und Steuerrecht; Verfahrensrecht'], ['Europarecht']]
但现在我np.sum这些列表:
np.sum(l)
np.sum(r)
我得到:
['a', 'b', 'a', 'c']
还有:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-158-0d0bce575128> in <module>()
----> 1 np.sum(r)
~/miniconda3/lib/python3.6/site-packages/numpy/core/fromnumeric.py in sum(a, axis, dtype, out, keepdims)
1832 return sum(axis=axis, dtype=dtype, out=out, **kwargs)
1833 return _methods._sum(a, axis=axis, dtype=dtype,
-> 1834 out=out, **kwargs)
1835
1836
~/miniconda3/lib/python3.6/site-packages/numpy/core/_methods.py in _sum(a, axis, dtype, out, keepdims)
30
31 def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
---> 32 return umr_sum(a, axis, dtype, out, keepdims)
33
34 def _prod(a, axis=None, dtype=None, out=None, keepdims=False):
TypeError: cannot perform reduce with flexible type
我完全不明白问题是什么。甚至打印这些列表中元素列表中的类型 [print(type(el[0])) for el in r];会给我<class 'str'>因此。类型是相同的——至少从我目前所知是这样 np.sum不适用于 r .
我不确定是否可以从您在此处看到的内容判断问题出在哪里。另外,我唯一可以提供的信息是 r来自已解析的 JSON - 但是,我不明白为什么这会影响结果。
请您参考如下方法:
使用np.sum 来展平您的列表是个坏主意。在执行 np.sum 之前,两个列表都被强制转换为具有不同 dtype 的 np 数组类型(尽管这略微撇开了失败的原因)。
np.array(l).dtype != np.array(r).dtype
您通常不想为此使用 np.sum。
使用列表理解以 Pythonic 方式简单地展平您的列表列表:
l = [x for lst in l for x in lst]
r = [x for lst in r for x in lst]
