两个python-li对元素分组

2024-10-02 18:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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。在


Tags: 文件intxt元素列表foraswith
3条回答
res = [ "{}\t{}\n".format(x,y) 
          for (x,y) in zip(datacolumn[0::2], datacolumn[1::2])]

…将为您提供一个行列表,其格式如您所需。在

注意,它假定有偶数对要格式化。在

您可以使用funcy库中的ipartition函数:

from funcy import ipartition

with open('filename.txt','w') as f:
    f.writelines('%s %d\n' % (label, num) 
                 for label, num in ipartition(2, datacolumn))

我使用临时列表a和b分别存储奇偶索引中的元素。在

datacolumn =    ['A1', -86, 'A2', 1839, 'A3', 2035, 'A4', 1849, 'A5', 1714]  
a=[datacolumn[x] for x in range(10) if x%2==0]
b=[datacolumn[x] for x in range(10) if x%2==1]
size=10
f=open("test.txt","w")
for i in range(size/2):
   f.write( a[i]+"\t" + str(b[i])+"\n")

希望有帮助。您可以找到有关列表理解的更多信息here

相关问题 更多 >