替换字典中的项目和格式化

时间:2017-10-22 09:40:09

标签: python

你好我是python的新手并且有一个问题。是否可以像列表一样格式化字典。

我的代码将这些项目放在这样的:

1294919 : (Person(1294919, 'Russel', 97.00, 1.90, 24, 0), 31022)

我希望它是这样的:

1294919 : Person(1294919, 'Russel', 97.00, 1.90, 24, 31022)

所以括号外的数字应该是0的位置。

代码:

{1665845: Person(1665845, 'Rurick', 101.00, 1.98, 75, 0), 1294919: Person(1294919, 'Russel', 97.00, 1.90, 24, 0)}

lines = [['1665845', '2001-01-06', '28,448,615,27,705'], ['1665845', '2001-01-10', '218,37,356,621,466,319,147,774,231,167,399,150,417,34,3'], ['1294919', '2001-01-04', '639,118,328,413,222,491,738,389,11,372,183,650,281,643,26,398,685,171'], ['1294919', '2001-01-10', '314,611,485,208,515,240,586,511,713,58,28,392,140,529,353,489,375,412,596'], ['1665845', '2001-01-04', '670,665,681,184,22,752,390,523,507,171,467,19,296,720,58,230,721,686'], ['1665845', '2001-01-02', '432,210,732,204,771,555,448,82,343'], ['1294919', '2001-01-06', '113,225,564,554,392,544,313'], ['1294919', '2001-01-05', '437,219,239,545,588,303,477,384,87,254,429,635,188,372,572,712,383'], ['1294919', '2001-01-03', '771,373'], ['1294919', '2001-01-08', '650,679,492,524,202,689,224,268,195,455,400,235,518,505']]

from collections import defaultdict
d_dict = defaultdict(int)
for k,_, v in lines:
    d_dict[int(k)]+=sum(int(i) for i in v.split(','))

for k in people:


    people[k] = people[k], d_dict[k]

人员类:

class Person:

def __init__(self, id_num, name, weight, height, age):                

    self.id_num = id_num
    self.name = name      
    self.weight = weight
    self.height = height
    self.age = age                   

1 个答案:

答案 0 :(得分:0)

你的问题不是很清楚。但是,如果我理解了你想要的东西,那么很大程度上取决于你所使用的Person课程。好像你需要更新它\创建一个新实例。 事情就是你最后一次像是在创建元组而不是Person,你需要做的就是这样:

for k in people:
    person = people[k]
    new_person = Person(person.id_num, person.name, person.weight, person.height, person.age, d_dict[k])
    people[k] = new_person