【问题标题】:How to retrieve the entire list just by inputting one element from that list?如何仅通过从列表中输入一个元素来检索整个列表?
【发布时间】:2022-12-07 18:05:49
【问题描述】:

当我输入与此人对应的号码时,姓名和生日等内容也应该出现

employInfo=[1,'De Leon','7/19/2001',
           2,'Fabian','6/6/1999'
           3,'Deseo','12/25/1998']
> output should be like:
Enter No.: 3
Employee with this No. is Deseo and his birthday is 12/25/1998.

我真的不知道我应该在这里做什么。

【问题讨论】:

  • 我也不知道。在哪里输入?如何?你试过什么?
  • 它总是跟随idnamedob吗?

标签: python list


【解决方案1】:

列表在这里是错误的数据结构,您应该使用字典:

d = {1: ['De Leon', '7/19/2001'],
     2: ['Fabian', '6/6/1999'],
     3: ['Deseo', '12/25/1998']}

inp = 3
name = d[inp][0]
birthday = d[inp][1]
output = f"Employee with this No. is {name} and his birthday is {birthday}."
print(output)

这打印:

Employee with this No. is Deseo and his birthday is 12/25/1998.

【讨论】:

    【解决方案2】:

    您应该创建一个类“Employee”并使用字典而不是列表:

    employInfo =
    {
        "1": employee1,
        "2": employee2
    }
    

    然后您可以通过其 ID 访问每个员工。您可以使用类方法来获取员工数据。

    【讨论】:

      【解决方案3】:
      employInfo = [1, 'De Leon', '7/19/2001',
                    2, 'Fabien', '6/6/1999',
                    3, 'Dereck', '12/25/1998']
      
      usr_input = int(input("Enter No.: "))
      num = usr_input - 1
      name = 2 * usr_input + num - 1
      date = usr_input * 3 - 1
      
      sentence = "Employee with this No. is " + 
      employInfo[name] + " and his birthday is " + 
      employInfo[date]
      
      print(sentence)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-24
        • 2020-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-08
        • 2011-09-27
        相关资源
        最近更新 更多