Python过滤器元素包含相同的参数

时间:2017-04-08 13:04:56

标签: python

我有三个词组列表

renting = [{'id': '92061083359', 'lp': '1', 'title': 'TITLE 1'}, {'id': '94103033254', 'lp': '2', 'title': 'TITLE 3'}, {'id': '92071176944', 'lp': '3', 'title': 'TITLE2'}, {'id': '93022138167', 'lp': '4', 'title': 'TITLE2'}]

students = [{'lastname': 'BAJOREK', 'id': '92051048757', 'name': 'JAKUB'}, {'lastname': 'SLOTARZ', 'id': '92051861424', 'name': 'MARIANNA'}, {'lastname': 'WNUK', 'id': '92052033215', 'name': 'SZYMON'}, {'lastname': 'LESKO', 'id': '92052877491', 'name': 'WOJCIECH'}]

rooms = [{'id_room': '8', 'id': '92061083359'}, {'id_room': '32', 'id': '94103033254'}, {'id_room': '47', 'id': '93022138167'}, {'id_room': '47', 'id': '92071176944'}]

我想过滤这个字典,只显示房间内相同的书名(id_room)。

输出

47号房间有2本重复的书籍(同一标题)。

我写了一些代码,但是效果不好

house_ids = set(report_dict['id'] for report_dict in report_student)
the_same = []
count = 0
# zliczanie tytulow ktore sa wyporzyczone kilka razy
for b in renting:
    count = 0
    stu = []
    for r in renting:
        if b.get('id') == r.get('title'):
            count += 1
            if count > 1:
                stu.append(r.get('id'))
    the_same.append(stu)

pesel_by_id = []

# sprawdzanie nr pesel w odniesieniu do mieszkania
for l in the_same:

    for pesel in l:
        tmp = []
        for mel in house_ids:
            if mel == pesel:
                tmp.append(mel)
    pesel_by_id.append(tmp)

count = 0

for x in pesel_by_id:
    for y in x:
        count += 1

1 个答案:

答案 0 :(得分:1)

您可以使用内置于Python中的filter

def search(id_room):
    book_id = filter(lambda a: a['id_room'] == id_room, rooms)[0]['id']
    title = filter(lambda a: a['id'] == book_id, renting)[0]['title']
    return len(filter(lambda a: a['title'] == title, renting))

print (search('47'))