0

我正在尝试编写一个简单的程序,让我输入一个姓名,然后它会搜索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."
4

5 回答 5

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."
于 2012-06-25T21:43:45.793 回答
1

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

于 2012-06-25T21:42:51.423 回答
1

This really should be something as:

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'))
于 2012-06-25T22:07:11.237 回答
1

First of all, note that in your example you are not using a list of tuples but a list of list. tuples are defined with normal brackets

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

Sequence access

In Python, list and tuple are sequences, so they can be accessed with numeric indices

For lists:

item = ["Shawn", 501], then you can do item[0] and item[1].

For tuples, it's exactly the same:

item = ("Shawn", 501), then you can do item[0] and item[1].

Unpacking

When your tuples are small, 'opening' them - unpacking being the Python term - is also very handy

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

Named tuples

Python 2.6 has introduced a namedtuple() type which you may find useful. With your example, you could do something like the following:

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."
于 2012-06-25T22:10:02.577 回答
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."
于 2012-06-25T21:54:52.230 回答