作爲替代方案,可以使用islice
給你所需要的數量每行的列如下:
from itertools import islice
import csv
path = 'output.txt'
values = range(105) # Create sample 'values' data
columns = 10
ivalues = iter(values)
with open(path, 'wb') as fp:
csv_output = csv.writer(fp)
for row in iter(lambda: list(islice(ivalues, columns)), []):
csv_output.writerow(row)
給你以下幾點:
0,1,2,3,4,5,6,7,8,9
10,11,12,13,14,15,16,17,18,19
20,21,22,23,24,25,26,27,28,29
30,31,32,33,34,35,36,37,38,39
40,41,42,43,44,45,46,47,48,49
50,51,52,53,54,55,56,57,58,59
60,61,62,63,64,65,66,67,68,69
70,71,72,73,74,75,76,77,78,79
80,81,82,83,84,85,86,87,88,89
90,91,92,93,94,95,96,97,98,99
100,101,102,103,104
注意,在你的榜樣,你應該轉換range
到xrange
,以避免Python創建一個龐大的數字列表進行迭代。
'close()'調用是不必要的。這就是'已經'在這裏已經做了。爲什麼索引'i'而不是'_directly_迭代'values'項呢? – BlackJack