枚举遍历在PAT上超时了一个测试点
n = int(input())
# info = []
# for i in range(n):
# t = []
# for j in range(6):
# t.append(input())
# info.append(t)
info = [[input() for __ in range(6)] for _ in range(n)] # 这两种写法等价
m = int(input())
def query(seq,key):
seq = int(seq)
ans = []
for i in range(n):
if seq == 3:# 要特判一下seq等于3的情况
keys = info[i][seq].split()
for x in keys:
if x == key:
ans.append(info[i][0])
break
elif info[i][seq] == key:
ans.append(info[i][0])
if not ans:
print("Not Found")
return
ans.sort()
for x in ans:
print(x)
for i in range(m):
q = input()
print(q)
seq,key = q.split(':')
key = key.strip()
query(seq,key)
方法二:可以使用多个字典
from collections import defaultdict
book = defaultdict(set)
author = defaultdict(set)
key_word = defaultdict(set)
publisher = defaultdict(set)
year = defaultdict(set)
n = int(input())
for i in range(n):
_id = input()
_book = input()
book[_book].add(_id)
_author = input()
author[_author].add(_id)
_key_word = input().split()
for item in _key_word:
key_word[item].add(_id)
_publisher = input()
publisher[_publisher].add(_id)
_year = input()
year[_year].add(_id)
m = int(input())
def query(seq, key):
seq = int(seq)
ans = []
if seq == 1:
for x in book[key]:
ans.append(x)
elif seq == 2:
for x in author[key]:
ans.append(x)
elif seq == 3:
for x in key_word[key]:
ans.append(x)
elif seq == 4:
for x in publisher[key]:
ans.append(x)
elif seq == 5:
for x in year[key]:
ans.append(x)
if not ans:
print("Not Found")
return
ans.sort()
for x in ans:
print(x)
for i in range(m):
q = input()
print(q)
seq, key = q.split(':')
key = key.strip()
query(seq, key)