python根据列名行名取数据_Python中的2D列表-通过列名访问

I'm parsing two files which has data as shown below

File1:

UID A B C D

------ ---------- ---------- ---------- ----------

456 536 1 148 304

1071 908 1 128 243

1118 4 8 52 162

249 4 8 68 154

1072 296 416 68 114

118 180 528 68 67

file2:

UID X Y A Z B

------ ---------- ---------- ---------- ---------- ---------

456 536 1 148 304 234

1071 908 1 128 243 12

1118 4 8 52 162 123

249 4 8 68 154 987

1072 296 416 68 114 45

118 180 528 68 67 6

I will be comparing two such files, however the number of columns might vary and the columns names. For every unique UID, I need to match the column names, compare and find the difference.

Questions

1. Is there a way to access columns by column names instead of index?

2. Dynamically give column names based on the file data?

I'm able to load the file into list, and compare using indexes, but thats not a proper solutions.

Thanks in advance.

解决方案

You might consider using csv.DictReader. It allows you both to address columns by names, and a variable list of columns for each file opened. Consider removing the ------ separating header from actual data as it might be read wrong.

Example:

import csv

with open('File1', 'r', newline='') as f:

# If you don't pass field names

# they are taken from the first row.

reader = csv.DictReader(f)

for line in reader:

# `line` is a dict {'UID': val, 'A': val, ... }

print line

If your input format has no clear delimiter (multiple whitespaces), you can wrap the file with a generator that will compress continous whitespaces into e.g. a comma:

import csv

import re

r = re.compile(r'[ ]+')

def trim_whitespaces(f):

for line in f:

yield r.sub(',', line)

with open('test.txt', 'r', newline='') as f:

reader = csv.DictReader(trim_whitespaces(f))

for line in reader:

print line

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值