python:对元组的算术运算导致TypeError

时间:2016-12-01 10:03:09

标签: python arrays tuples

所以我有两个不同的二维数组wordsscores

words是一个二维的字符串数组 scores是float的二维数组

我将它们转换为元组并对它们执行算术运算(我最初将元组传递给执行该操作的库,但为了简单起见,我复制了操作并开始对其进行测试)

我的代码

for i in range(0,len(scores)):
    freqs = []
    for word, score in zip(words[i], scores[i]):
        freqs.append((word, score))
        frequencies = [ (word, freq / 20.0) for word, freq in freqs ]

当我运行此代码时,我收到以下错误

TypeError                                 Traceback (most recent call last)
<ipython-input-17-017692219adb> in <module>()
      4     for word, score in zip(words[i], scores[i]):
      5         freqs.append((word, score))
----> 6         frequencies = [ (word, freq / 20.0) for word, freq in freqs ]
      7 
      8         #elements = wc.fit_words(freqs)

TypeError: unsupported operand type(s) for /: 'str' and 'float'

2 个答案:

答案 0 :(得分:4)

freq是一个字符串。在分裂之前转换为浮动。

例如:float(freq)

因此新代码将为frequencies = [ (word, float(freq) / 20.0) for word, freq in freqs ]

答案 1 :(得分:1)

错误基本上是说你试图用浮点数划分一个字符串,所以你必须将字符串转换为浮点数:

for i in range(0,len(scores)):
    freqs = []
    for word, score in zip(words[i], scores[i]):
        freqs.append((word, score))
        frequencies = [ (word, float(freq) / 20.0) for word, freq in freqs ]