Delete item in a list using a for-loop

前端 未结 5 1202
感情败类
感情败类 2021-01-13 17:35

I have an array with subjects and every subject has connected time. I want to compare every subjects in the list. If there are two of the same subjects, I want to add the ti

5条回答
  •  长情又很酷
    2021-01-13 18:09

    An alternate way would be to create the subject and time lists anew, using a dict to sum up the times of recurring subjects (I am assuming subjects are strings i.e. hashable).

    subjects=['math','english','necromancy','philosophy','english','latin','physics','latin']
    time=[1,2,3,4,5,6,7,8]
    tuples=zip(subjects,time)
    my_dict={}
    for subject,t in tuples:
        try:
            my_dict[subject]+=t
        except KeyError:
            my_dict[subject]=t
    subjects,time=my_dict.keys(), my_dict.values()
    print subjects,time
    

提交回复
热议问题