【问题标题】:How can I print an unknown number of dictionary keys using a list to identify keys?如何使用列表打印未知数量的字典键来识别键?
【发布时间】:2018-10-05 12:39:03
【问题描述】:

所以我搜索并找到了一些有助于我将这段代码组合在一起的东西,但我对最后一部分没有任何运气。我想要做的是读取逗号分隔、空格分隔或制表符分隔的文件,将标题设置为键,将数据设置为值,然后仅将某些列(列数未知)写入输出文件。 Example.txt 如下所示:

col1, col2, col3, col4, col5
1, 11, 21, 31, 41
2, 12, 22, 32, 42
3, 13, 23, 33, 43
4, 14, 24, 34, 44

到目前为止,这是我到目前为止的工作代码。

import csv
import sys

file = sys.argv[1] # name of file is example.txt
columns = sys.argv[2:] # order: col1, col3, col5

with open(file, 'r') as csvfile:
    with open('table.out', 'w') as file_out:
        file.out_write(columns[0] + '\t' + columns[1] + '\t' + columns[2] + '\n')

        reader = csv.DictReader(csvfile)
        for row in reader:
            file_out.write(row[columns[0]] + '\t' + row[columns[1]] + '\t' + row[columns[2]] + '\n') 

结果:

col_1    col_3    col_5
1    21    41
2    22    42
3    23    43
4    24    44

如果列数是固定数字,则此代码效果很好,但要写入的列数可能会有所不同。例如,有时我可能只想抓取 col1、col2,而其他时候我可能想不按特定顺序抓取 col2、col3、col4、col5。

所以我的问题是,如何修改上述代码,以便可以使用 Python 3.X 中的字典将任意数量的列写入输出文件?

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:
    import csv
    import sys
    
    file = sys.argv[1] # name of file is example.txt
    columns = sys.argv[2:] # order: col1, col3, col5
    n_columns=len(columns)
    
    with open(file, 'r') as csvfile:
        with open('table.out', 'w') as file_out:
            for i in range(0,n_columns):
                file_out.write(columns[i] + '\t')
            file_out.write('\n')
    
            reader = csv.DictReader(csvfile)
            for row in reader:
                for i in range(0,n_columns):
                    file_out.write(row[columns[i]] + '\t')
                file_out.write('\n')
    

    所以,我稍微修改了您的代码。 要编写可变数量的列,您可以使用从 0 到列列表长度的 for 语句。

    【讨论】:

      【解决方案2】:

      您可以根据自己的需要调整它,但基本上使用 join 函数会非常有帮助 + 列表理解。

      import csv
      import sys
      
      file = sys.argv[1]
      columns = sys.argv[2:]
      
      with open(file) as f:
          myread = csv.DictReader(f)
          for row in myread:
              print('\t'.join([row[i] for i in columns]))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多