【问题标题】:Python, swap variables every loopPython,每个循环交换变量
【发布时间】:2017-11-30 07:10:53
【问题描述】:

我的部分代码如下所示:

for i in [0,1]:
    ...
    print('{} used {} words that {} did not use.'.format(a[i], 50 , a[i+1]))

对于第一次迭代,我希望它这样做,

print('{} used {} words that {} did not use.'.format(a[0], 50 , a[1]))

但是对于第二次迭代,我想要这个:

print('{} used {} words that {} did not use.'.format(a[1], 50 , a[0]))

如何做到这一点?

【问题讨论】:

  • 1 - i 是一种选择。
  • (i+1)%2 是另一个
  • i ^ 1 也可以
  • 我认为这里要问的内容不是很清楚。所需的解决方案应该如何推广到更长的循环,例如迭代[0,1,2,3,4]?或者,Eric,[0,1] 是您想要处理的唯一案例吗?如果是这样,为什么不写两个 print() 语句并完成它?
  • 我会说,如果它只有两个项目,那么删除循环以提高可读性。

标签: python python-3.x swap


【解决方案1】:

您可以使用模运算符%

for i in [0,1]:
    ...
    print('{} used {} words that {} did not use.'.format(a[i % 2], 50 , a[(i + 1) % 2]))

在第一次迭代中,i = 0

i % 2       == 0 % 2 == 0
(i + 1) % 2 == 1 % 2 == 1

在第二次迭代中,i = 1

i % 2       == 1 % 2 == 1
(i + 1) % 2 == 2 % 2 == 0

请注意,第一个 i % 2 == i 用于您的问题的这个特定实例。

【讨论】:

    【解决方案2】:

    您可以使用指数模 2 (%2):

    a = ['first', 'second']
    
    for idx in [0, 1]:
        print('{} used {} words that {} did not use.'.format(a[idx%2], 50 , a[(idx+1)%2]))
    

    输出:

    first used 50 words that second did not use.
    second used 50 words that first did not use.
    

    或者,如果只有两个项目:

    这样做可能更容易阅读和维护:

    a = ['first', 'second']
    x, y = a
    print('{} used {} words that {} did not use.'.format(x, 50 , y))
    print('{} used {} words that {} did not use.'.format(y, 50 , x))
    

    【讨论】:

      【解决方案3】:

      如果这正是您想要的,您可以这样做:

      for i in [0,1]:
          ...
          print('{} used {} words that {} did not use.'.format(a[i], 50 , a[(i+1)%2]))
      

      【讨论】:

        【解决方案4】:

        这是我的解决方案:

        a = ['John','Doe']
        amount = 50
        
        # Use index to create strings to be formatted
        s1 = '{0} used {2} words that {1} did not use.'
        s2 = '{1} used {2} words that {0} did not use.'
        
        print(s1.format(*a,amount))
        print(s2.format(*a,amount))
        

        返回:

        John used 50 words that Doe did not use.
        Doe used 50 words that John did not use.
        

        或者:

        # Use index to create strings to be formatted
        s = '''\
        {0} used {2} words that {1} did not use.
        {1} used {2} words that {0} did not use.'''
        
        print(s.format(*a,amount))
        

        返回:

        John used 50 words that Doe did not use.
        Doe used 50 words that John did not use.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-08-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-13
          • 2015-01-26
          相关资源
          最近更新 更多