我想用list comprehension将一组2个的元素从一个列表写入一个txt文件。在
datacolumn = ['A1', -86, 'A2', 1839, 'A3', 2035, 'A4', 1849, 'A5', 1714, ...]
所以文件名.txt=
^{pr2}$我找到了一个将element写成一列的解决方案:
with open('filename.txt','w') as f:
f.writelines( "%s\n" % item for item in datacolumn)
我一时想不出怎么做。我做了一个循环:
with open('filename.txt','w') as f:
for i in range(0,size(datacolumn),2):
f.write(str(datacolumn[i])+"\t"+str(datacolumn[i+1])+"\n")
但我更喜欢使用理解列表。我使用的是python2.7。在
…将为您提供一个行列表,其格式如您所需。在
注意,它假定有偶数对要格式化。在
您可以使用funcy库中的ipartition函数:
我使用临时列表a和b分别存储奇偶索引中的元素。在
希望有帮助。您可以找到有关列表理解的更多信息here
相关问题 更多 >
编程相关推荐