使用python以CSV格式查找列号

时间:2016-11-18 09:00:35

标签: python csv

我想匹配CSV文件中的某个字符串,并返回CSV文件中字符串的column,例如

import csv
data = ['a','b','c'],['d','e','f'],['h','i','j']

例如,我正在寻找单词e,我希望它返回[1],因为它在第二列中。

4 个答案:

答案 0 :(得分:1)

使用csv.reader对象和enumerate函数的解决方案(获取键/值序列):

def get_column(file, word):
    with open(file) as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            for k,v in enumerate(row):
                if v == word:
                    return k  # immediate value return to avoid further loop iteration

search_word = 'e'
print(get_column("data/sample.csv", search_word))  # "data/sample.csv" is an exemplary file path

输出:

1

答案 1 :(得分:0)

我不确定为什么在这个例子中你需要csv

>>> data = ['a','b','c'],['d','e','f'],['h','i','j']
>>> 
>>> 
>>> string = 'e'
>>> for idx, lst in enumerate(data):
...     if string in lst:
...             print idx

1

答案 2 :(得分:0)

尝试以下方法:

>>> data_list = [['a','b','c'],['d','e','f'],['h','i','j']] 
>>> col2_list = []
>>> 
>>> for d in data_list:
...     col2=d[1]
...     col2_list.append(col2)

所以最后你得到一个包含列[1]的所有值的列表:

col2_list = ["b","e","i"]

答案 3 :(得分:0)

wolendranh的回答:

>>> data = ['a','b','c'],['d','e','f'],['h','i','j']
>>> word = 'e'
>>> for row in data:
...     try:
...         print(row.index(word))
...     except ValueError:
...         continue