python如何查找列表元素
如果你想坚持你的模式,这是一个选择:
search = {'Age' : 21, 'Gender' : 'M'}
idxs = [ (main_col.index(key), val) for key, val in search.items()]
tmp = [ set(tuple(person) for person in main_row if person[i] == v) for i, v in idxs ]
res = set.intersection(*tmp)
#=> {('Wade', 21, 'M'), ('Malcom', 21, 'M')}
注:
我用过
intersection
AND
,但您可以自定义上可用的任何操作
set
https://docs.python.org/3.7/library/stdtypes.html#set
):
union
,
交叉
difference
, ...
您可以转换为方便的方法:
def lookup(search, main_row, main_col):
idxs = [ (main_col.index(key), val) for key, val in search.items()]
tmp = [ set(tuple(person) for person in main_row if person[i] == v) for i, v in idxs ]
return set.intersection(*tmp)
lookup({'Age' : 21}, main_row, main_col)
#=> {('Wade', 21, 'M'), ('Mellisa', 21, 'F'), ('Malcom', 21, 'M')}
lookup({'Age' : 21, 'Gender' : 'M'}, main_row, main_col)
#=> {('Malcom', 21, 'M'), ('Wade', 21, 'M')}
lookup({'Age' : 21, 'Gender' : 'M', 'Name': 'Malcom'}, main_row, main_col)
#=> {('Malcom', 21, 'M')}
main_row = [['Peter', 18, 'M'], ['Sam', 20, 'M'], ['Carol', 19, 'F'], ['Malcom', 21, 'M'], ['Oliver', 25, 'M'], ['Mellisa', 21, 'F'], ['Minreva', 18, 'F'], ['Bruce', 23, 'M'], ['Clarke', 24, 'M'], ['Zuck', 22, 'M'], ['Slade', 23, 'M'], ['Wade', 21, 'M'], ['Felicity', 22, 'F'], ['Selena', 23, 'F'], ['Ra\'s Al Gul',700, 'M'], ['Oliver', 31, 'M']]
这就构成了字典
people
,将头的第一个列表分开:
people = [ {'name':name, 'age':age, 'gender':gender} for name, age, gender in main_row]
#=> [{'name': 'Peter', 'age': 18, 'gender': 'M'}, {'name': 'Sam', 'age': 20, 'gender': 'M'}, ....
next(person for person in people if person['name'] == 'Oliver' and person['age'] == 31 )
#=> {'name': 'Oliver', 'age': 31, 'gender': 'M'}
the_21_years_old = [ person for person in people if person['age'] == 21 ]
#=> [{'name': 'Malcom', 'age': 21, 'gender': 'M'}, {'name': 'Mellisa', 'age': 21, 'gender': 'F'}, {'name': 'Wade', 'age': 21, 'gender': 'M'}]
您可以对返回的“记录”执行任何需要的操作:
for person in the_21_years_old:
print(person['name'], person['age'])
# Malcom 21
# Mellisa 21
# Wade 21