繁体   English   中英

Python:如何在每次迭代时更改变量?

[英]Python:how to change variable at each iteration?

我希望能够在我的循环的每次迭代中打印包含向量“数字”的字符串“名称”中存在的不同变量,以这种方式:

one x=1 y=2
two x=3 y=4
three x=5 y=6
four x=7 y=8
five x=9 y=10

我该怎么做? 目前我只能编写这部分代码:

numbers=(1,2,3,4,5,6,7,8,9,10)
names=('one', 'two', 'three', 'four', 'five')
for i in range (0, len(num)-1,2):
     x=numbers[i]
     y=numbers[i+1]
     print('x=', x, 'y=', y)

请记住,数组从 0 开始,您可以从

names = ['zero', 'one', 'two', 'three', 'four']

names的值无关紧要,但zero有所帮助。

现在你可以看到你想要的是,对于每个名字,打印它代表的值( i ),然后是2*i + 12*i + 2

zero   1  2
one    3  4
two    5  6
three  7  8
four   9  10

由于name的值无关紧要,只有它们的位置,您可以从one开始再次计数。

所以这是我的解决方案。 简单,只有三行:

names = ['one', 'two', 'three', 'four', 'five']

for i in range (len(names)):
     print(names[i], 'x =', 2*i+1, 'y =', 2*i+2)


如果您想保留numbers或进行最小的更改,这里是 Alessandro Artoni 的答案的修复:

numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
names = ('one', 'two', 'three', 'four', 'five')

for i in range (0, len(names)):
     x = numbers[i]*2-1
     y = numbers[i]*2
     print(names[i], 'x=', x, 'y=', y)



根据您的评论,这是输出到文件的方法:

names = ['one', 'two', 'three', 'four', 'five']

with open('output.txt', 'w') as f:
    for i in range (len(names)):
         f.write(names[i] + '  x = ' + str(2*i+1) + '  y = ' + str(2*i+2) + '\n')

或者,由于您选择了 tobias_k 的答案:

numbers = range(1, 11)
names = ('one', 'two', 'three', 'four', 'five')
result = [(a, *b) for a, b in zip(names, zip(*[iter(numbers)]*2))]

with open('output.txt', 'w') as f:
    for element in result
        f.write("%s  x=%d  y=%d\n" % element)

解决您的问题的最小变化是:

numbers=(1,2,3,4,5,6,7,8,9,10)
names=('one', 'two', 'three', 'four', 'five')
for i in range (0, len(names)):
     x=numbers[i]
     y=numbers[i+1]
     print(names[i], 'x=', x, 'y=', y)

我还建议您列出 '[]' 而不是元组 '()'。 享受!

所需的输出是:

one x=1 y=2
two x=3 y=4
three x=5 y=6
four x=7 y=8
five x=9 y=10

所以我很快把它放在一起:

result = ""
max_number = 10

names = ['one', 'two', 'three', 'four', 'five']
y = 0
for i in range (1, max_number, 2):
    result +='%s x=%d y=%d\n' % (names[y], i, i+1)
    y += 1

print(result)

所以基本上我连接每一行并在最后打印所有内容。 您也可以随时打印。 剩下的就是添加一些验证以使其健壮:)

您可以使用zip(*[iter(lst)]*n)配方来迭代值对,并使用名称zip它们。 (即第一zip似乎有点难以理解。基本上,它创建一个iter从列表中,那么zips的两个引用该ITER在一起,从而导致对连续元素的)。

>>> numbers=(1,2,3,4,5,6,7,8,9,10)
>>> names=('one', 'two', 'three', 'four', 'five')
>>> [(a, *b) for a, b in zip(names, zip(*[iter(numbers)]*2))]
[('one', 1, 2),
 ('two', 3, 4),
 ('three', 5, 6),
 ('four', 7, 8),
 ('five', 9, 10)]

一旦你有了这些元组,你就可以使用格式字符串来打印它们(或将它们写入一个文件with open("name", "w") as f: for ...: f.write(...) )

for t in [(a, *b) for a, b in zip(names, zip(*[iter(numbers)]*2))]:
    print("%s x=%d y=%d" % t)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM