Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

string - Why does my Python code thinks a variable is a str when it should be an int?

So we are making a Python program in class in which we extract data about road accidents. The file we are extracting from is a table with each line giving information about the people involved in a given accident

usagers_2016 = open('usagers_2016.csv','w',encoding='utf8', errors='ignore', newline="
")
usagers_2016.write("Num_Acc;place;catu;grav;sexe;trajet;secu;locp;actp;etatp;an_nais;num_veh

201600000001;1;1;1;2;0;11;0;0;0;1983;B02

201600000001;1;1;3;1;9;21;0;0;0;2001;A01

201600000002;1;1;3;1;5;11;0;0;0;1960;A01

201600000002;2;2;3;1;0;11;0;0;0;2000;A01

201600000002;3;2;3;2;0;11;0;0;0;1962;A01

201600000003;1;1;1;1;1;11;0;0;0;1997;A01
")

next(usagers_2016)

dict_acc = {}

for ligne in usagers_2016.readlines():
    ligne = ligne[:-2].split(";")

I chose to extract the info in a dictionnary, where the accident is the key, the value of each key is a list, whose first element is a list of the people involved, each person being represented by a list including their gender and birth year

    if ligne[0] not in dict_acc.keys():
        dict_acc[ligne[0]] = [[],0,0,0,0]
    dict_acc[ligne[0]][0].append([ligne[4],ligne[10]])

usagers_2016.close()

for accident in dict_acc:
    accident[1] = len(accident[0]) # TypeError: 'str' object does not support item assignment

My problem is the following: I want to add, as the second element of the main list (the value of the key), the number of people involved in each accident (which is the len() of the first element (list) of the list). However it was revealed during the running of the code that the first 0 (line 2 of the previous code extract) is considered a str and can't receive item assignment whatsoever. The problem is that it was supposed to be an int!!!! I thought that expliciting the int type as following dict_acc[ligne[0]] = [[],int(0),int(0),int(0),int(0)] would correct it, but no, my 0s are still considered strings. Would you know why?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

OK so the problem was that I was calling accident[1] instead of dict_acc[accident][1]

solution is

for accident in dict_acc:
    dict_acc[accident][1] = len(dict_acc[accident][0])

I thank @MisterMiyagi


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...