[英]Why am I seeing "TypeError: string indices must be integers"?
我正在學習 Python 並嘗試將 GitHub 問題轉換為可讀形式。 使用有關如何將 JSON 轉換為 CSV 的建議? ,我想出了這個:
import json
import csv
f = open('issues.json')
data = json.load(f)
f.close()
f = open("issues.csv", "wb+")
csv_file = csv.writer(f)
csv_file.writerow(["gravatar_id", "position", "number", "votes", "created_at", "comments", "body", "title", "updated_at", "html_url", "user", "labels", "state"])
for item in data:
csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])
其中“issues.json”是包含我的 GitHub 問題的 JSON 文件。 當我嘗試運行它時,我得到
File "foo.py", line 14, in <module>
csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])
TypeError: string indices must be integers
我在這里想念什么? 哪些是“字符串索引”? 我敢肯定,一旦我得到這個工作,我會有更多的問題,但現在,我只是喜歡這個工作!
當我將for
語句調整為簡單
for item in data:
print item
我得到的是……“問題”——所以我做錯了一些更基本的錯誤。 這是我的一些 JSON 內容:
{"issues": [{"gravatar_id": "44230311a3dcd684b6c5f81bf2ec9f60", "position": 2.0, "number": 263, "votes": 0, "created_at": "2010/09/17 16:06:50 -0700", "comments": 11, "body": "Add missing paging (Older>>) links...
當我打印data
時,它看起來真的很奇怪:
{u'issues': [{u'body': u'Add missing paging (Older>>) lin...
變量item
是一個字符串。 索引如下所示:
>>> mystring = 'helloworld'
>>> print mystring[0]
'h'
上面的示例使用字符串的0
索引來引用第一個字符。
字符串不能有字符串索引(就像字典一樣)。 所以這行不通:
>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers
item
很可能是代碼中的字符串; 字符串索引是方括號中的索引,例如gravatar_id
。 所以我首先檢查你的data
變量,看看你在那里收到了什么; 我猜data
是一個字符串列表(或者至少是一個包含至少一個字符串的列表),而它應該是一個字典列表。
str[a:b]
在str[a:b]
的兩個索引a
和b
之間使用冒號:
而不是逗號,
my_string[0,5] # wrong ❌
my_string[0:5] # correct ✅
在使用字符串和切片表示法( 常見的序列操作)時,可能會TypeError
,指出索引必須是整數,即使它們顯然是整數。
>>> my_string = "Hello, World!"
>>> my_string[0,5]
TypeError: string indices must be integers
我們顯然將兩個整數作為索引傳遞給切片符號,對吧? 那么這里的問題是什么?
這個錯誤可能非常令人沮喪——尤其是在開始學習 Python 時——因為錯誤信息有點誤導。
當我們調用my_string[0,5]
時,我們將兩個整數的tuple
隱式傳遞給切片表示法。 0,5
計算為與(0,5)
相同的元組 - 即使沒有括號。 為什么呢?
結尾的逗號,
實際上足以讓 Python 解釋器將某些內容評估為元組:
>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>
所以我們在那里做了什么,這一次是明確的:
>>> my_string = "Hello, World!"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers
現在,至少,錯誤信息是有意義的。
我們需要用冒號替換逗號,
以正確分隔兩個整數,而不是將它們解釋為tuple
:
>>> my_string = "Hello, World!"
>>> my_string[0:5]
'hello'
更清晰、更有幫助的錯誤消息可能類似於:
TypeError: string indices must be integers not tuple
^^^^^
(actual type here)
一個好的錯誤信息應該直接向用戶展示他們做錯了什么! 有了這種信息,找到根本原因和解決問題會容易得多——而且您不必來這里。
所以下一次,當你發現自己有責任編寫錯誤描述消息時,提醒自己這個例子並將原因(或其他有用的信息)添加到錯誤消息中! 幫助其他人(或者甚至是你未來的自己)了解哪里出了問題。
:
來分隔其索引(和步長范圍,即str[from:to:step]
),
(即t = 1,
) data
是一個dict
對象。 所以,像這樣迭代它:
for key, value in data.iteritems():
print key, value
for key, value in data.items():
print(key, value)
我對 Pandas 有類似的問題,您需要使用 iterrows() 函數來遍歷 Pandas 數據集Pandas 文檔 for iterrows
data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
print('{} {}'.format(item["gravatar_id"], item["position"]))
請注意,您需要處理函數返回的數據集中的索引。
根據經驗,當我在 Python 中收到此錯誤時,我會將函數簽名與函數執行進行比較。
例如:
def print_files(file_list, parent_id):
for file in file_list:
print(title: %s, id: %s' % (file['title'], file['id']
因此,如果我將調用此函數並使用以錯誤順序放置的參數並將列表作為第二個參數和一個字符串作為第一個參數傳遞:
print_files(parent_id, list_of_files) # <----- Accidentally switching arguments location
該函數將嘗試迭代parent_id
字符串而不是file_list
,並且它希望將索引視為指向字符串中特定字符的整數,而不是作為字符串( title
或id
)的索引。
這將導致TypeError: string indices must be integers
錯誤。
由於其動態特性(與 Java、C# 或 Typescript 等語言相反),Python 不會通知您此語法錯誤。
將小寫字母轉換為大寫:
str1 = "Hello How are U"
new_str = " "
for i in str1:
if str1[i].islower():
new_str = new_str + str1[i].upper()
print(new_str)
錯誤 :
TypeError:字符串索引必須是整數
解決方案 :
for i in range(0, len(str1))
// Use range while iterating the string.
如何讀取這個 JSON 的第一個元素? 當文件看起來像這樣
for i in data[1]:
print("Testing"+i['LocalObservationDateTime'])
這對我不起作用。 下面是 JSON 文件
[ { "LocalObservationDateTime":"2022-09-15T19:05:00+02:00", "EpochTime":1663261500, "WeatherText":"Mostly cloudy", "WeatherIcon":6, "HasPrecipitation":false, "PrecipitationType":"None", "IsDayTime":true, "Temperature":{ "Metric":{ "Value":11.4, "Unit":"C", "UnitType":17 }, "Imperial":{ "Value":52.0, "Unit":"F", "UnitType":18 } }, "RealFeelTemperature":{ "Metric":{ "Value":8.4, "Unit":"C", "UnitType":17, "Phrase":"Chilly" } } }, { "LocalObservationDateTime":"2022-09-16T19:05:00+02:00", "EpochTime":1663261500, "WeatherText":"Mostly cloudy", "WeatherIcon":6, "HasPrecipitation":false, "PrecipitationType":"None", "IsDayTime":true, "Temperature":{ "Metric":{ "Value":11.4, "Unit":"C", "UnitType":17 }, "Imperial":{ "Value":52.0, "Unit":"F", "UnitType":18 } }, "RealFeelTemperature":{ "Metric":{ "Value":8.4, "Unit":"C", "UnitType":17, "Phrase":"Chilly" } } } ]
如果缺少逗號,可能會發生這種情況。 當我有一個雙元組列表時,我遇到了它,每個元組都由第一個位置的字符串和第二個位置的列表組成。 在一種情況下,我錯誤地在元組的第一個組件之后省略了逗號,解釋器認為我正在嘗試索引第一個組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.