对于列表列表上的循环

2024-06-14 06:57:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,其中包含一些数据,我希望能够调用列表的内容,但只能调用某些内容,例如:empList[0][0]empList[0][1]。我希望能够对列表中的每个项目执行此操作,然后从列表的该部分调用所选索引,例如:empList[0][0]empList[0][1]empList[1][0]empList[1][1],但在for循环中。 我的参考代码:

empList = [
    ['51-4678119', 'Issie', 'Scholard', '11 Texas Court', 'Columbia', 'Missouri', '65218', '3', '134386.51', '34', '91.06'],
    ['68-9609244', 'Jed', 'Netti', '85 Coolidge Terrace', 'San Antonio', 'Texas', '78255', '2', '159648.55', '47', '45.7'],
    ['47-2771794', 'Galvan', 'Solesbury', '3 Drewry Junction', 'Springfield', 'Illinois', '62794', '2', '91934.89', '39', '47.92']
]
emp = employee(empList[0][0], empList[0][1], empList[0][2], empList[0][3], empList[0][4], empList[0][5], empList[0][6], empList[0][7])

希望这是有道理的。谢谢大家!


Tags: 数据项目代码内容列表fortexasjed
3条回答

您可以使用:

emp = employee(*empList[0][:8])

这可能类似于您正在寻找的:

from collections import namedtuple

empList = [
    ['51-4678119', 'Issie', 'Scholard', '11 Texas Court', 'Columbia', 'Missouri', '65218', '3', '134386.51', '34', '91.06'],
    ['68-9609244', 'Jed', 'Netti', '85 Coolidge Terrace', 'San Antonio', 'Texas', '78255', '2', '159648.55', '47', '45.7'],
    ['47-2771794', 'Galvan', 'Solesbury', '3 Drewry Junction', 'Springfield', 'Illinois', '62794', '2', '91934.89', '39', '47.92']
]
Employee = namedtuple('Employee', 'ID First Last Street City State Zip Ham Salary Eggs Spam')
employees = [Employee(*e) for e in empList]

print(employees[0])
print(employees[1].State)
print(employees[2].Ham)

Employee(ID='51-4678119', First='Issie', Last='Scholard', Street='11 Texas Court', City='Columbia', State='Missouri', Zip='65218', Ham='3', Salary='134386.51', Eggs='34', Spam='91.06')
Texas
2

如果参数的顺序始终正确,则可以执行以下操作:

employees = [employee(*args) for args in empList]

相关问题 更多 >