Python,每个循环交换变量

时间:2017-11-30 07:10:54

标签: python python-3.x swap

我的部分代码如下所示:

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]))

如何做到这一点?

4 个答案:

答案 0 :(得分:1)

如果这正是您正在寻找的,您可以这样做:

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

答案 1 :(得分:1)

您可以使用indice modulo 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))

答案 2 :(得分:1)

您可以使用modulous运算符%

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

答案 3 :(得分:0)

这是我的解决方案:

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.