“TypeError : 문자열 인덱스는 정수 여야합니다”가 표시되는 이유는 무엇입니까?
나는 파이썬을 배우고 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
코드의 문자열 일 가능성이 높습니다. 문자열 인덱스는 대괄호 안에있는 인덱스입니다 (예 :) gravatar_id
. 먼저 data
변수를 확인하여 거기에서받은 것을 확인합니다 . 나는 data
그것이 사전의 목록이어야하지만 문자열 목록 (또는 적어도 하나의 문자열을 포함하는 목록)이라고 생각합니다.
변수 item
는 문자열입니다. 색인은 다음과 같습니다.
>>> mystring = 'helloworld'
>>> print mystring[0]
'h'
위의 예는 0
문자열 의 색인을 사용 하여 첫 번째 문자를 나타냅니다.
문자열은 사전과 같이 문자열 인덱스를 가질 수 없습니다. 그래서 이것은 작동하지 않습니다 :
>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers
data
A는 dict
객체. 따라서 다음과 같이 반복하십시오.
파이썬 2
for key, value in data.iteritems():
print key, value
파이썬 3
for key, value in data.items():
print(key, value)
슬라이스 표기법의 TypeError str[a:b]
tl;dr: use a colon :
instead of a comma in between the two indices a
and b
in str[a:b]
When working with strings and slice notation (a common sequence operation), it can happen that a TypeError
is raised, pointing out that the indices must be integers, even if they obviously are.
Example
>>> my_string = "hello world"
>>> my_string[0,5]
TypeError: string indices must be integers
We obviously passed two integers for the indices to the slice notation, right? So what is the problem here?
This error can be very frustrating - especially at the beginning of learning Python - because the error message is a little bit misleading.
Explanation
We implicitly passed a tuple of two integers (0 and 5) to the slice notation when we called my_string[0,5]
because 0,5
(even without the parentheses) evaluates to the same tuple as (0,5)
would do.
A comma ,
is actually enough for Python to evaluate something as a tuple:
>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>
So what we did there, this time explicitly:
>>> my_string = "hello world"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers
Now, at least, the error message makes sense.
Solution
We need to replace the comma ,
with a colon :
to separate the two integers correctly:
>>> my_string = "hello world"
>>> my_string[0:5]
'hello'
A clearer and more helpful error message could have been something like:
TypeError: string indices must be integers (not tuple)
A good error message shows the user directly what they did wrong and it would have been more obvious how to solve the problem.
[So the next time when you find yourself responsible for writing an error description message, think of this example and add the reason or other useful information to error message to let you and maybe other people understand what went wrong.]
Lessons learned
- slice notation uses colons
:
to separate its indices (and step range, e.g.str[from:to:step]
) - tuples are defined by commas
,
(e.g.t = 1,
) - add some information to error messages for users to understand what went wrong
Cheers and happy programming
winklerrr
[I know this question was already answered and this wasn't exactly the question the thread starter asked, but I came here because of the above problem which leads to the same error message. At least it took me quite some time to find that little typo.
So I hope that this will help someone else who stumbled upon the same error and saves them some time finding that tiny mistake.]
This can happen if a comma is missing. I ran into it when I had a list of two-tuples, each of which consisted of a string in the first position, and a list in the second. I erroneously omitted the comma after the first component of a tuple in one case, and the interpreter thought I was trying to index the first component.
'development' 카테고리의 다른 글
하위 프로세스 명령의 라이브 출력 (0) | 2020.06.01 |
---|---|
XML 스키마와 DTD의 차이점은 무엇입니까? (0) | 2020.06.01 |
JWT를 도난 당하면 어떻게됩니까? (0) | 2020.06.01 |
두 개의 ActiveRecord :: Relation 객체를 결합 (0) | 2020.06.01 |
표준 Kotlin 라이브러리에서 사용할 수있는 Java 8 Stream.collect는 무엇입니까? (0) | 2020.06.01 |