代码之家  ›  专栏  ›  技术社区  ›  user7852656

Python 3中zip函数的格式。x(错误消息:zip参数#1必须支持迭代)

  •  0
  • user7852656  · 技术社区  · 7 年前

    我一直在研究如何格式化我的zip函数。我知道zip函数只接受iterable对象(列表、集、元组、字符串、迭代器等)。到目前为止,我正在尝试生成一个输出文件,在所有单独的列中压缩三个浮点值。如果能得到一些反馈,告诉我如何在获得相同结果的同时解决这个问题,我将不胜感激。
    仅供参考,纽约输入文件有如下内容。。

    1600     1
    1700     3
    1800     2.5
    3000     1
    7000     5
    

    import numpy as np
    import os
    import csv
    
    myfiles = os.listdir('input') 
    
    for file in myfiles:
        size=[]
        norm_intensity=[]    
        with open('input/'+file, 'r') as f:
            data = csv.reader(f,delimiter=',') 
            next(data)
            next(data)
            for row in data:
                size.append(float(row[0]))
                norm_intensity.append(float(row[1]))
    
            x_and_y = []
            row = np.array([list (i) for i in zip(size,norm_intensity)])
            for x, y in row:
                if y>0:       
                    x_and_y.append((x,y))
    
        """""""""""""""""
        Sum of intensity from the first pool
        """""""""""""""""            
    
        first_x=[]
        first_y= []
        for x,y in (x_and_y):
            if x>1600 and x<2035.549:
                first_x.append(x)
                first_y.append(y)
    
        first_sum=np.sum(first_y)
    

    以类似的方式,我得到了第二个和和第三个和(每个都有不同的x范围)。

    first_pool=first_sum/(first_sum+second_sum+third_sum)
    second_pool=second_sum/(first_sum+second_sum+third_sum)
    third_pool=third_sum/(first_sum+second_sum+third_sum)
    
    with open ('output_pool/'+file, 'w') as f:
        for a,b,c in zip(first_pool,second_pool,third_pool):        
            f.write('{0:f},{1:f},{2:f}\n'.format(a,b,c))
    

    first_pool     second_pool      third_pool
    (first_sum)    (second_sum)     (third_sum)
    

    由于first\u pool、second\u pool、third\u pool都是浮点数,所以我当前看到的消息是, zip argument #1 must support iteration . 你有什么建议我仍然可以实现这个目标吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   scnerd    7 年前

    据我所知,你不需要拉链。以下内容应该满足您的需要:

    sums = [first_sum, second_sum, third_sum]
    pools = [first_pool, second_pool, third_pool]
    ...
    for a,b,c in [pools, sums]:
        f.write('{0:f},{1:f},{2:f}\n'.format(a,b,c))
    

    例如,如果您有这两个列表,并且想要成对的总和和池,则压缩就是:

    for pool, summation in zip(pools, sums):
        f.write('Pool: {}, Sum: {}'.format(pool, summation))
        # Pool: 0.5, Sum: 10
        # Pool: 0.3, Sum: 6
        # ...