例如,如果我有一个列表:courses = [{name: a, course: math, count:1}]如果我再次输入 name: a course: math 列表将是 courses = {name: a, course: math, count:2}我只希望具有相同名称的项目和课程不会附加到列表中,而只会增加“计数”关键项目。我试过 :def add_class(inputname,inputcourse):for i in (len(courses)): if courses[i]['name']== inputname and courses[i]['course']==inputcourse: courses[i][count]+=1 else : newdata = {"name":inputname, "course":inputcourse,count:1} #i put count because this item is the first time. courses.append(newdata) print courses我希望输出是 class ={name: a, course: math, count:2}但实际输出是 class =[{name: a, course: math, count:2},{name: a, course: math, count:1}] 如果我输入一个新数据,如 name : a, course: physic 输出将是 [{name:a,course:physic,count:1},{name: a, course: math, count:2},{name: a, course: math, count:1}]
2 回答
沧海一幻觉
TA贡献1824条经验 获得超5个赞
您可以使用 for else 子句。只有在没有达到 break 时才会调用 else 部分,这是一个例子
courses = []
courses.append({'name': 'a', 'course': 'math', 'count': 1})
def add_course(d):
for course in courses:
if course['course'] == d['course'] and course['name'] == d['name']:
course['count'] += 1
break
else:
d['count'] = 1
courses.append(d)
add_course({'name': 'a', 'course': 'math'})
add_course({'name': 'a', 'course': 'english'})
print(courses)
作为输出,你有 [{'name': 'a', 'course': 'math', 'count': 2}, {'name': 'a', 'course': 'english', 'count': 1}]
添加回答
举报
0/150
提交
取消