python - 数组中值比较的Pythonic方法?

标签 python arrays csv rows

问题:

  1. 输入是制表符分隔的文件。行是变量,列是样本。变量可以采用三个值(00,01,11),并按照需要维护的顺序列出(v1->vN)。输入文件的行数和列数较多,需要分块读取。

    输入如下所示:

       s1 s2 s3 s4
    v1 00 00 11 01
    v2 00 00 00 00
    v3 01 11 00 00
    v4 00 00 00 00
    (...)
    
  2. 我想做的是将输入分成几行的片段,这些片段足够大,每个样本都是唯一的。在上面的示例中,从 v1 开始,第一个 block 应在 v3 结束,因为此时有足够的信息表明样本是唯一的。下一个 block 将从 v4 开始并重复该过程。当到达最后一行时任务结束。这些 block 应打印在输出文件中。

<小时/>

我的尝试:

我想做的是使用 csv 模块生成一个由列表组成的数组,每个列表包含所有样本的单个变量 (00,01,00) 的状态。或者,通过旋转输入,创建包含每个变量的样本状态的列表。我问工作应该集中在列还是行上,即使用 v1=['00','00','11','01'] 还是 s1 更好=['00','00','01','00',...]

以下代码引用了我尝试将列问题更改为行问题的旋转操作。 (抱歉,笨拙的Python语法,这是我能做的最好的)

my_infilename='my_file.txt'
csv_infile=csv.reader(open(my_infilename,'r'), delimiter='\t')
out=open('transposed_'+my_infilename, 'w')
csv_infile=zip(*csv_infile)
line_n=0
for line in csv_infile:
line_n+=1
    if line_n==1:    #headers
        continue
    else:
        line=(','.join(line)+'\n')  #just to make it readable to me
        out.write(line)
out.close()

解决这个问题的最佳方法是什么?旋转有什么帮助吗?有什么我可以依赖的内置函数吗?

最佳答案

假设您将 csv 数据导入为长度相同的列表列表,这对您有何作用...

def get_block(data_rows):
    samples = []

    for cell in data_rows[0]:
        samples.append('')

    # add one row at a time to each sample and see if all are unique
    for row_index, row in enumerate(data_rows):
        for cell_index, cell in enumerate(row):
            samples[cell_index] = '%s%s' % (samples[cell_index], cell)

        are_all_unique = True
        sample_dict = {} # use dictionary keys to find repeats
        for sample in samples:
            if sample_dict.get(sample):
                # already there, so another row needed
                are_all_unique = False
                break
            sample_dict[sample] = True # add the key to the dictionary
        if are_all_unique:
            return True, row_index

    return False, None

def get_all_blocks(all_rows):
    remaining_rows = all_rows[:] # make a copy    
    blocks = []

    while True:
        found_block, block_end_index = get_block(remaining_rows)
        if found_block:
            blocks.append(remaining_rows[:block_end_index+1])
            remaining_rows = remaining_rows[block_end_index+1:]
            if not remaining_rows:
                break
        else:
            blocks.append(remaining_rows[:])
            break

    return blocks


if __name__ == "__main__":
    v1 = ['00', '00', '11', '01']
    v2 = ['00', '00', '00', '00']
    v3 = ['01', '11', '00', '00']
    v4 = ['00', '00', '00', '00']

    all_rows = [v1, v2, v3, v4]

    blocks = get_all_blocks(all_rows)

    for index, block in enumerate(blocks):
        print "This is block %s." % index
        for row in block:
            print row
        print

==================

这是 block 0。

['00'、'00'、'11'、'01']

['00', '00', '00', '00']

['01'、'11'、'00'、'00']

这是 block 1。

['00', '00', '00', '00']

关于python - 数组中值比较的Pythonic方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10194191/

相关文章:

arrays - 将 `ByVal` 参数传递给 Regex 函数会导致代码非常慢,尽管使用 Array

javascript - UseState 不会在 componentDidMount 生命周期方法中更新

python - to_csv() 写入带有附加分数的值

python - 添加两个具有混合边缘的图像

python - 代码 8 : Loading a plug-in failed

javascript - 使用 ObjectID 删除特定记录

Python PIP 安装问题

C++ 读入用逗号和空格分隔的文件

php - 将 csv 文件上传到 Mysql/PHP

node.js - 不知道如何使用 csv-writer 在 API 调用后逐行写入 csv 文件