基于共同的价值链接两个列表

时间:2017-11-07 16:00:41

标签: python python-2.7

我是Python 2.7的新手,我希望第1列成为员工的关键列,并且必须检查dept 1st列并生成结果。

员工来自文本文件,部门来自数据库。我尝试了很多,但没有得到一个简单的答案。我的代码出了什么问题?

**Inputs :**

employees=['1','peter','london']
employees=['2','conor','london']
employees=['3','ciara','london']
employees=['4','rix','london']

dept=['1','account']
dept=['2','developer']
dept=['3','hr']

**Expected Output :**

results=['1','peter','london','account']
results=['2','conor','london','developer']
results=['3','ciara','london','hr']
results=['4','rix','london',null]

2 个答案:

答案 0 :(得分:0)

你的输入毫无意义。每行都以数据方式覆盖前一行。这里似乎数字(作为字符串)是键,当dept中没有找到任何信息时,必须执行一些默认操作。

要保持精神,只需创建2个词典,然后使用词典理解来生成结果:

employees = dict()
dept = dict()

employees['1'] = ['peter','london']
employees['2'] = ['conor','london']
employees['3'] = ['ciara','london']
employees['4'] = ['rix','london']

dept['1']=['account']
dept['2']=['developer']
dept['3']=['hr']

result = {k:v+dept.get(k,[None]) for k,v in employees.items()}

print(result)

产生包含所有信息的字典。请注意,null在python中是None

{'1': ['peter', 'london', 'account'], '4': ['rix', 'london', None], '3': ['ciara', 'london', 'hr'], '2': ['conor', 'london', 'developer']}

答案 1 :(得分:0)

你可以去上课。考虑一下:

class Employee:
     def __init__(self, number, name, location, dept):
          self.number = str(number)
          self.name = name
          self.location = location
          self.dept = dept

     def data(self):
          return [self.number,
                  self.name,
                  self.location,
                  self.dept]

peter = Employee(1, 'peter', 'london', 'account')
print(peter.data())

['1', 'peter', 'london', 'account']
>>>