2015-12-02 78 views
0

我有一个雇员的记录,它会要求他们输入他们的名字和工作,并添加这两种元素的元组。我已经完成了它,以便它首先添加到列表中,然后转换为元组。Python的元组和列表

但是我只想打印雇员姓名中的作业以及。

我试图做最后的线print(mytuple[0])但这也不管用。

record=[] 
mytuple=() 

choice = "" 
while (choice != "c"): 
    print() 
    print("a. Add a new employee") 
    print("b. Display all employees") 

    choice = input("Choose an option") 
    if choice == "a": 
     full_name = str(input("Enter your name: ")).title() 
     record.append(full_name) 
     print(record) 

     job_title = str(input("Enter your job title: ")).title() 
     record.append(job_title) 
     print(record) 


    elif choice == "b": 
     print("Employee Name:") 
     for n in record: 
      mytuple=tuple(record) 
      print(mytuple) 
+0

请注意,您的问题不是关于元组和列表之间的任何差异;出于您的目的,它们几乎完全相同,唯一的区别是您无法附加到元组。 –

回答

1

你似乎过于单一record是迭代的,即一个列表。听起来好像你认为你有一个列表(“记录”)的列表,但你从来没有创建该结构。

很明显,如果你迭代列表中的字符串,从每个字符串构建一个元素元组,然后打印它,你将最终打印列表中的所有字符串。

0

您应该使用字典,如果你想访问特定领域name.In Python列表就像数组,如果你能取回索引序列,那么你将能够看到你的结果。

,但我的建议使用字典,然后将其转换成元组。这对你有好处。

0

您将full_namejob_title作为单独的实体附加到您的记录阵列中。你想要的是像这样添加一个新员工时:

full_name = str(input("Enter your name: ")).title() 
job_title = str(input("Enter your job title: ")).title() 
record.append((full_name, job_title)) 
print(record[-1]) 

然后显示所有员工的名字:

​​
0

你应该做一个列表records(有用的名称,它拥有许多记录),并添加list(我们调用这个变量record)为每一位员工。

records=[] # a new list, for all employees 
# mytuple=() # you don't need this 

choice = "" 
while (choice != "c"): 
    print() 
    print("a. Add a new employee") 
    print("b. Display all employees") 

    choice = input("Choose an option") 
    if choice == "a": 

     record = list() # create new list for employee 

     full_name = str(input("Enter your name: ")).title() 
     record.append(full_name) 
     print(record) 

     job_title = str(input("Enter your job title: ")).title() 
     record.append(job_title) 
     print(record) 


    elif choice == "b": 
     print("Employee Name:") 
     for record in records: 

      print(record[0]) # record will be a list with first the name, then the title 
      print(record[1])