python、zip:Discard 额外元素

python, zip:Discard extra elements

我想生成优惠券编号到.txt,我在调用它时将元素数量设置为参数。

我使用 zip() 迭代写入两列中的 .txt。但是当我设置一个奇数时zip总是丢弃一个元素。

这是我的代码:

for i, j in zip(coupon[0::2], coupon[1::2]):
    w.writelines(j + '\t' + i + '\n')

如何处理?

此外,如果我试图让一行10列,这里怎么写?

for a, b, c, ....j in ~~:

这将是愚蠢的,我无法输入 \t 9 次。

谢谢!

您可以使用打印功能的文件选项,来自内置帮助:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

print(j, i, sep='\t', end='\n', file = w)

您可以单步执行并切掉要加入的块。

以下函数将按制表符分隔的列打印数据或将其写入传递的文件:

import sys

def write_cols(data,n,f = sys.stdout):
    for chunk in (data[i:i+n] for i in range(0,len(data),n)):
        print('\t'.join(chunk), file = f)

例如,如果 data = ['a','b','c','d','e','f','g','h'] 那么:

>>> write_cols(data,3)
a   b   c
d   e   f
g   h

>>> f = open("testfile.txt",'w')
>>> write_cols(data,3,f)
>>> f.close()

将向该文件发送相同的输出。