2015-12-02 103 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])