Python在嵌套元组中查找字符串

时间:2015-12-03 18:47:42

标签: python

我有一个数据库,我希望能够搜索一个名称,即如果名称是Mark Kram,它将显示具有该名称的用户,我不需要它是名称为“Mark”的每个人或“Kram”,但只输入字符串。我当前的代码,只显示每个用户而不是我搜索的用户?

(根据评论进行编辑以删除多余的代码)

  find = str(input("Enter the name of the employee you would like to search for: "))
  print()
  for find in record:
      print("Employee Name: " + find[0])
      print("Job title: " + find[1])
      #more prints

3 个答案:

答案 0 :(得分:1)

您必须在每个元组中的第一个项目(全名)上查找匹配项。

elif choice == "c":
    find = str(input("Enter the name of the employee you would like to search for: "))
    print()
    for employee in record:
        if employee[0] == find:
            print("Employee Name: " + employee[0])
            print("Job title: " + employee[1])
            print("Full time: " + employee[2])
            print("Hourly Rate: " + employee[3])
            print("Years of service: " + str(employee[4]))
            print()

您的代码是开始了解class es。

的一个很好的例子

答案 1 :(得分:0)

根据记录的数量,我会采用简单的路线并遍历记录,查找员工的姓名:

empName = "Mark Kram"
for record in records:
  if record[0] == empName:
    print "we found the employee!"
    print record #print the whole employee record

答案 2 :(得分:0)

那是因为你在没有任何条件的情况下迭代你的所有记录和打印。您还要立即覆盖查询字符串。

elif choice == "c":
    find = str(input("Enter the name of the employee you would like to search for: "))
    print()
    for employee in record:
        if employee[0] == find:
            print("Employee Name: " + employee[0])
            print("Job title: " + employee[1])
            print("Full time: " + employee[2])
            print("Hourly Rate: " + employee[3])
            print("Years of service: " + str(employee[4]))
            print()