将用户插入的元素添加到列表中

时间:2016-05-13 19:53:51

标签: python python-2.7 python-3.x

你好我试图将元素添加到列表但我不知道为什么元素(UserName& Salary)没有添加到列表中, 我尝试了很多,但我不知道我在这里失踪了什么..!

由于

class emp():
empCount=0


count = 0
while (count < 3):
    def __init__(self,name=input('entername:'),Salary=input('Enter Employee Salary: ')):
        empList = []
        self.name=name
        empList.append(name)

        self.Salary=Salary
        empList.append(self.Salary)

        emp.empCount = +1

    #def Emp_Salary(self):
        print ('Name:', self.name, 'Salary:', self.Salary)

        print ('total Employee %d' % emp.empCount)

        print empList
    count = count + 1

2 个答案:

答案 0 :(得分:2)

empList = []移出while

正如您在问题的评论中所提到的,您想要将元素添加到列表中,这是一个示例。

list_employ = []

for i in range(3):
    name = input('Entername: '),
    salary = input('Enter Employee Salary: ')

    list_employ.append([name, salary])

print(list_employ)

测试,

$ python stackoverflow.py 
Entername: 'a'
Enter Employee Salary: 1
Entername: 'b'
Enter Employee Salary: 2
Entername: 'c'
Enter Employee Salary: 3
[['a', 1], ['b', 2], ['c', 3]]

答案 1 :(得分:0)

谢谢你们

解决方案是:

class emp():
empList = []
  def A(self,name,Salary):

    self.name=name
    self.Salary=Salary

    print ('Name:', name, 'Salary:', Salary)


 for x in range(3):
  a=emp()
  a.A(input('enter Name'),input('Enter Salary'))
  a.empList.append([a.name,a.Salary])
  x +=1

print (emp.empList)

Thes输出:

enter Name'a'
Enter Salary1
('Name:', 'a', 'Salary:', 1)
enter Name'b'
Enter Salary2
('Name:', 'b', 'Salary:', 2)
enter Name'c'
Enter Salary3
('Name:', 'c', 'Salary:', 3)
[['a', 1], ['b', 2], ['c', 3]]