2016-12-01 50 views
1

因此,我已兩個不同的2維陣列wordsscores蟒:在類型錯誤上元組結果的算術操作

words是串 scores的2維數組是浮體的2維陣列

我將它們轉換爲元組並對它們執行算術運算(我最初將元組傳遞給庫,但爲了簡單起見,我複製了操作並開始測試它)

我的代碼

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' 
+0

你確定'freq'(在你的綜合列表中)包含數字而不是字符串嗎? – Daneel

回答

4

freq是一個字符串。在分割之前轉換爲浮點數。

如:float(freq)

所以新的代碼將frequencies = [ (word, float(freq)/20.0) for word, freq in freqs ]

1

什麼錯誤,基本上說的是,你正在試圖通過一個浮動分割字符串,所以你必須將字符串轉換爲float:

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 ]