【问题标题】:Python Using IF inside FOR loopPython 在 FOR 循环中使用 IF
【发布时间】:2013-09-28 22:30:50
【问题描述】:

这个问题可能很傻,但我正在尝试使用字典来迭代并返回结果。我知道如何遍历字典,但我想检查输入的键是否存在于字典中,并且我希望程序打印该值是否存在。

class companyx:

    def __init__(self,empid):

        self.empid=empid

    def employees(self):

        employees={1:'Jane',2:'David',3:'Chris',4:'Roger'}

        entered=self.empid

        for emp in employees :
            if emp == entered:
                print ('Hi '+employees[emp] +' you are an employee of companyx.com')
        print('You dont belong here')

emp=companyx(2)

emp.employees()

当我传递一个不在字典中的参数时,我希望函数打印“你不属于这里”

【问题讨论】:

    标签: python if-statement for-loop dictionary


    【解决方案1】:

    检查一个键是否在字典中的最简单(也是最惯用的)方法是:

    if entered in employees:
    

    以上代码替换了您代码的for/if 部分。请注意,不需要显式遍历字典,in 运算符负责检查成员资格。简短而甜蜜:) 完整的代码如下所示:

    def employees(self):
        employees = {1:'Jane', 2:'David', 3:'Chris', 4:'Roger'}
        if self.empid in employees:
            print('Hi ' + employees[self.empid] + ' you are an employee of companyx.com')
        else:
            print("You don't belong here")
    

    【讨论】:

    • +1 这样你就不需要编写循环部分(因为它在幕后做任何事情)
    • 是的,你可以迈克尔:x = {'pie':'thon'} ; assert('pie' in x )...呵呵你知道我的意思:)
    • @TehTris:幕后没有循环。另外,{'pie','thon'} 是一个集合。
    【解决方案2】:

    使用in 关键字快速执行字典查找:

    if entered in employees:
        # the key is in the dict
    else:
        # the key could not be found
    

    【讨论】:

      【解决方案3】:

      试试这个:

      if entered in employees.keys():
          ....
      else:
          ....
      

      【讨论】:

      • 不需要keys():if entered in employees。
      【解决方案4】:

      您无需遍历字典即可执行此操作。你可以写:

      def employees(self):
      
          employees={1:'Jane',2:'David',3:'Chris',4:'Roger'}
          employee = employees.get(self.empid)
      
          if employee:
              print ('Hi ' + employee + ' you are an employee of companyx.com')
          else:
              print ('You dont belong here')
      

      【讨论】:

        【解决方案5】:

        最pythonic的方法是尝试查找,如果发生故障则处理:

        try:
            print('Hi '+employees[entered] +' you are an employee of companyx.com')
        except KeyError:
            print('You dont belong here')
        

        for 循环没有任何理由;字典的全部意义在于您可以一步查找内容d[key],而不必遍历键并检查每个键是否== key。

        您可以使用in 来检查密钥是否存在,然后查找它。但这有点傻 - 你正在查找密钥以查看是否可以查找密钥。为什么不直接查一下钥匙呢?

        您可以使用get 方法执行此操作,如果缺少密钥,该方法将返回None(或者您可以传递不同的默认值):

        name = employees.get(entered)
        if name:
            print('Hi '+name +' you are an employee of companyx.com')
        else:
            print('You dont belong here')
        

        但它是Easier to Ask Forgiveness than Permission。除了稍微简洁一点之外,使用try 和except 可以清楚地表明,找到名称是应该正确的正常情况,而没有找到它是例外情况。

        【讨论】:

        • +1 使用try/except 确实是 Pythonic 方式来解决这个问题
        【解决方案6】:

        不需要 for 循环 - 你只需要:

        if entered in employees:
            print 'blah'
        else:
            print 'You do not belong here'
        

        【讨论】:

          猜你喜欢
          • 2023-01-13
          • 1970-01-01
          • 1970-01-01
          • 2021-07-01
          • 1970-01-01
          • 2011-12-23
          • 2019-07-31
          • 2014-03-13
          相关资源
          最近更新 更多