4 回答

TA贡献1775条经验 获得超11个赞
请记住数组从 0 开始,您可以从
names = ['zero', 'one', 'two', 'three', 'four']
里面的值names并不重要,但从zero帮助开始。
现在您可以看到您想要的是,对于每个名称,打印它代表的值 ( i),然后2*i + 1和2*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)

TA贡献1871条经验 获得超8个赞
您可以使用zip(*[iter(lst)]*n)配方来迭代值对以及zip带有名称的值对。(这首先zip看起来有点神秘。基本上它iter从列表中创建一个,然后zips将该迭代的两个引用放在一起,从而产生连续元素对。)
>>> 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)

TA贡献1827条经验 获得超9个赞
所需的输出是:
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)
所以基本上我连接每一行并在最后打印所有内容。您也可以边走边打印。剩下的就是添加一些验证以使其稳健:)

TA贡献1860条经验 获得超9个赞
解决您的问题的最小更改是:
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)
我还建议您使用列表“[]”而不是元组“()”。享受!
添加回答
举报