Python元组搜索

时间:2012-06-25 21:37:37

标签: python for-loop python-2.7 if-statement

我正在尝试编写一个简单的程序,让我输入一个名称,然后它将搜索employeeList以查看该人是否是经理。如果员工人数为500或更大,则该人员将成为经理。

因此,以["David", 501]为例,如何仅指定条件语句中的数字部分?我已经使用item作为名称,但我不知道如何指定数字。谢谢!

#!/usr/bin/python

input = raw_input("Please enter name to determine if employee is a manager: ")

employeeList = [["Shawn", 500], ["David", 501], ["Ted", 14], ["Jerry", 22]]

for item in employeeList :
    print "Employee Name is: ", item
    if item == input and item >= 500:
        print "This person is a manager."
    else:
        print "This person is not a manager."

5 个答案:

答案 0 :(得分:3)

您可以使用数字索引来引用列表中的特定元素。由于您正在使用列表列表,因此我们可以引用item循环变量之外的索引。

这是你的for循环相应调整:

for item in employeeList:
  print "Employee name is: %s" % (item[0])
  if item[0] == input and item[1] >= 500:
    print "This person is a manager."
  else:
    print "This person is not a manager."

答案 1 :(得分:1)

item[0]将是名称,item[1]是他们的员工编号。

答案 2 :(得分:1)

这应该是:

lookup = dict( (name, ' is a manager' if num >= 500 else ' is not a manager') for name, num in employeeList)
print '{}{}'.format(some_name_from_somewhere, lookup.get(some_name_from_somewhere, ' is not known'))

答案 3 :(得分:1)

首先,请注意,在您的示例中,您没有使用元组列表,而是使用列表列表。元组用普通括号定义

("I", "am", "a", "tuple")

序列访问

在Python中,listtuplesequences,因此可以使用数字索引访问它们

列表:

item = ["Shawn", 501],然后您可以item[0]item[1]

对于元组,它完全相同:

item = ("Shawn", 501),然后您可以item[0]item[1]

启封

当你的元组很小时,'打开'它们 - unpacking是Python术语 - 也非常方便

item = ("Shawn", 501)
name, number = item # We unpack the content of the tuple into some variables

命名元组

Python 2.6引入了namedtuple()类型,您可能会发现它很有用。在您的示例中,您可以执行以下操作:

Employee = namedtuple("Employee", ['name', 'number'])
employeeList = [
    Employee("Shawn", 500),
    Employee("David", 501),
    Employee("Ted", 14],
    Employee("Jerry", 22)
]
for item in employeeList:
    if item.name == name and item.number >= 500:
        print "This person is a manager."
    else:
        print "This person is not a manager."

答案 4 :(得分:0)

打印出列表中的每个项目有什么意义?

您只需要找到被查询的人并检查他/她是否是经理

#!/usr/bin/python

input = raw_input("Please enter name to determine if employee is a manager: ")

employeeList = [["Shawn", 500], ["David", 501], ["Ted", 14], ["Jerry", 22]]
employeeDict = dict(employeeList)

if input in employeeDict:
    if employeeDict[input] > 500:
        print "This person is a manager."
    else:
        print "This person is not a manager."
else:
    print "This person is not an employee."