使用条件语句在Python列表中搜索元素

时间:2019-01-04 17:34:15

标签: python python-3.x

main_col = ['Name', 'Age', 'Gender']
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']]

我正在尝试编写一个程序,其中main_col是列名,而main_row具有每一列的行信息(在2d列表中)。

如何为搜索查询编写一段代码,该代码可以搜索以下位置的行:

  1. 姓名=“卡罗尔”,年龄= 19。
  2. 姓名=“卡罗尔”,性别=“ F”
  3. 年龄= 22或性别='M'

以下代码给出了第三部分的结果:-

search = {'Age' : 22, 'Gender' : 'M'}

for i in search:
    idx = main_col.index(i)
    for j in main_row:
        if(j[idx] == search[i]):
            print(j)

2 个答案:

答案 0 :(得分:2)

您可以尝试一下,它有些复杂,但是应该可以完成工作:

AND = 'and'
OR = 'or'

# Check if the array is a match
def is_found(value, aggregator, search_terms):
  if aggregator == AND:
    is_found = True
    for col, val in search_terms.items():
      if value[val['idx']] != val['val']:
        is_found = False
        break
  else:
    is_found = False
    for col, val in search_terms.items():
      if value[val['idx']] == val['val']:
        is_found = True
        break
  return is_found

# Perform the search
def search(columns, values, aggregator, search_filters):
  # Format the search values into something we can use
  # {
  #    'col': { 'idx': <column index>, 'val': <search value> }
  # } 
  search_terms = { 
    col: { 'idx': columns.index(col), 'val': val } 
    for col, val in search_filters.items()
  }

  return [
    val
    for val in values
    if is_found(val, aggregator, search_terms)
  ]

if __name__ == "__main__":
  main_col = ['Name', 'Age', 'Gender']
  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']]

  search_filter = {
    'Age': 22, 'Gender': 'M'
  }
  print(search(main_col, main_row, OR ,search_filter))

  search_filter = {
    'Name': 'Carol', 'Age': 19
  }
  print(search(main_col, main_row, AND ,search_filter))

答案 1 :(得分:1)

如果您想坚持自己的模式,可以选择以下选项:

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,但是您可以自定义sethttps://docs.python.org/3.7/library/stdtypes.html#set)上可用的任何操作:unionintersectiondifference,...


您可以转换为方便的方法:

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中的字典:

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