<p>下面是一个完整的例子。你知道吗</p>
<p>此脚本不使用任何库,在<code>Python 2.7</code>中运行。只要确保每个值都用逗号分隔,就可以创建CSV(逗号分隔值)文件。另外,我没有使用<code>itertools</code>,而是使用<code>map</code>函数。你知道吗</p>
<pre><code># Python 2.7
# Here is an example of three lists of different lengths
aList = [9,8,2,5,14,6]
bList = [8,7,5,4]
cList = [9,15,25,60,47,88,3]
# Creates your empty CSV file
output_file = open(r'C:\Temp\output.csv', 'w')
# Adds headers in the first row
output_file.write('aList,bList,cList\n')
# Adds all the elements from the lists, row-by-row
for a, b, c in map(None, aList, bList, cList):
output_file.write('%s,%s,%s\n' % (a, b, c))
# Closes your file
output_file.close()
</code></pre>
<p>在<code>Python 3</code>中,<code>map</code>函数不再支持<code>None</code>作为映射函数。在这种情况下,来自<code>itertools</code>库的<code>zip_longest</code>函数可能是最干净的方法(注意,在<code>Python 2.7</code>中,来自<code>itertools</code>的函数称为<code>izip_longest</code>)</p>
<pre><code># Python 3.x
import itertools
# Here is an example of three lists of different lengths
aList = [9,8,2,5,14,6]
bList = [8,7,5,4]
cList = [9,15,25,60,47,88,3]
# Creates your empty CSV file
output_file = open(r'C:\Temp\output.csv', 'w')
# Adds headers in the first row
output_file.write('aList,bList,cList\n')
# Adds all the elements from the lists, row-by-row
for a, b, c in itertools.zip_longest(aList, bList, cList):
output_file.write('%s,%s,%s\n' % (a, b, c))
# Closes your file
output_file.close()
</code></pre>