繁体   English   中英

Python元组和列表

[英]Python tuples and lists

我有一个员工记录,它将要求他们输入姓名和工作并将这两个元素添加到元组中。 我这样做了,以便它首先添加到列表中,然后转换为元组。

但是我只想打印雇员姓名而不是工作。

我试图print(mytuple[0])最后一行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)

您似乎在遍历单个record (即列表)。 听起来好像您认为自己有一个列表列表(“记录”),但从未创建该结构。

显然,如果您遍历列表中的字符串,从每个字符串中构建一个1元素元组,然后进行打印,最终将打印列表中的所有字符串。

如果要访问特定的字段名称,则应使用字典。在python列表中,就像数组一样,如果可以获取索引序列,则可以看到结果。

但我的建议是使用字典,然后将其转换为元组。 它将对您有益。

您要将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])

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

for name, _ in record:
    print(name)

您应该创建一个列表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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM