我正在尝试编写一个简单的程序,让我输入一个名字,然后它会搜索 employeeList 以查看此人是否是经理。 如果此人的员工人数为 500
或更大,则该人将成为经理。
因此,以["David", 501]
为例,如何在条件语句中仅指定数字部分? 我已经使用了项目作为名称,但不确定该怎么做才能指定数字。 谢谢!
#!/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."
您可以使用数字索引来引用列表中的特定元素。 由于您使用的是列表列表,因此我们可以从 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."
item[0]
将是姓名,并item[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'))
首先,请注意,在您的示例中,您使用的不是元组列表,而是列表列表。 元组是用普通括号定义的
("I", "am", "a", "tuple")
序列访问
在 Python 中,list
和 tuple
是序列,因此可以使用数字索引访问它们
对于列表:
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."
打印出列表中的每个项目有什么意义?
您只需要找到被查询的人并检查他/她是否是经理
#!/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."