【问题标题】:How to Look inside a Dict/List and get the position and a bool [duplicate]如何查看字典/列表并获取位置和布尔值 [重复]
【发布时间】:2021-05-16 19:22:55
【问题描述】:

我想知道当有人进入时是否无论如何,比如说'070718604545'。它查找它,如果它在那里,它会在列表中打印其他人,示例如下

Patt = [
                {'Phone': "0718604545", 'Name': "Tom", 'Age': '2007'}
                {'Phone': "0718123567", 'Name': "Katy", 'Age': '1998'}
                {'Phone': "0718604578", 'Name': "BillyW", 'Age': '1970'}
                 ....
                 ....
                 ....
                 ....
                {'Phone': "0714565778", 'Name': "Sony", 'Age': '1973'}
            ]

他会输入'0718604545'作为例子。

x = input("Enter Phone")
Search for x in Patt[Phone]:
   name = Patt[Name] where Phone = x
   print(name)

所以答案应该是汤姆。

谢谢,

【问题讨论】:

  • 如果多人拥有相同的电话号码,您期望什么结果?

标签: python python-3.x list dictionary python-requests


【解决方案1】:

您可以通过遍历列表 patt 来获取号码,然后访问 patt 项目中的每个电话键,并使用 == 运算符与您要查找的电话号码进行比较。下面的函数可以完成这项工作。

def answer(search):
    for data in patt: # iterate over each item in patt
        if data["Phone"] == search: # compare the current value if it is the searched one
            return data["Name"] # return the name in the dictionary when the number is found
    return None # if it is not found, return None
print(answer('0718604545'))

【讨论】:

    【解决方案2】:

    下面应该工作。对于每个项目,检查“电话”键是否具有匹配 x 的值。如果是,则返回 'name' 键的值。

    x = input("Enter Phone")
    for item in Patt:
      if item["Phone"] == x:
        print(item["Name"])
    

    【讨论】:

      【解决方案3】:

      在准备答案时,我没有注意到一个正确的答案已经发布并被接受。不过,在下面发布我的答案版本,增加了连续提问的功能和退出程序的能力。

      Patt = [
          {'Phone': "0718604545", 'Name': "Tom", 'Age': '2007'},
          {'Phone': "0718123567", 'Name': "Katy", 'Age': '1998'},
          {'Phone': "0718604578", 'Name': "BillyW", 'Age': '1970'},
          {'Phone': "0714565778", 'Name': "Sony", 'Age': '1973'}
      ]
      
      print(Patt)
      
      
      def search_phone_records(user_phone):
          for record in Patt:  # Iterate over all the phone records in the dictionary
              if user_phone == record['Phone']:  # stop if found phone number in the dictionary
                  return record['Name']  # Return user's name from the phone record
          return None
      
      
      while True:
          user_input = input("Enter Phone or press 'x' to exit: ")
      
          if user_input in ('x', 'X'):
              print("Have a nice day!!! Thank you using our service!!!")
              break  # End the programme
      
          # Search for the phone number
          user_name = search_phone_records(user_input)
      
          #print("[{0}]".format(user_name))
          if type(user_name) == type(None):  # Phone number is not found
              print("Oops!!! Entered phone number ({0}) is not found in the dictionary!!!".format(user_input))
          else:  # Phone number is found
              print("Entered phone number ({0}) is found in the dictionary!!!".format(user_input))
              print("It is {1}'s phone number.".format(user_input, user_name))
      

      使用字典理解的另一种解决方案:

      Patt = [
          {'Phone': "0718604545", 'Name': "Tom", 'Age': '2007'},
          {'Phone': "0718123567", 'Name': "Katy", 'Age': '1998'},
          {'Phone': "0718604578", 'Name': "BillyW", 'Age': '1970'},
          {'Phone': "0714565778", 'Name': "Sony", 'Age': '1973'}
      ]
      
      print(Patt)
      
      
      def search_phone_records_using_dictionary_comprehension(user_phone):
          return {'Name': record['Name'] for record in Patt if user_phone == record['Phone']}
      
      
      while True:
          user_input = input("Enter Phone or press 'x' to exit: ")
      
          if user_input in ('x', 'X'):
              print("Have a nice day!!! Thank you using our service!!!")
              break  # End the programme
      
          result = search_phone_records_using_dictionary_comprehension(user_input)
          print("result = {0}".format(result))
      
          if len(result) == 0:   # Phone number is not found
              print("Oops!!! Entered phone number ({0}) is not found in the dictionary!!!".format(user_input))
          else:  # Phone number is found
              print("Entered phone number ({0}) is found in the dictionary!!!".format(user_input))
              print("It is {1}'s phone number.".format(user_input, result['Name']))
      

      【讨论】:

        猜你喜欢
        • 2017-10-23
        • 2023-03-11
        • 2019-06-04
        • 2018-05-13
        • 1970-01-01
        • 2020-04-18
        • 2021-11-02
        • 2019-12-15
        • 1970-01-01
        相关资源
        最近更新 更多