<p>所以您想从csv文件中选择与特定列的特定值相对应的行?在Python2.7中是这样吗?好吧,这对2.7来说并不难</p>
<p>使用<a href="https://docs.python.org/2/library/csv.html" rel="nofollow noreferrer">csv.DictReader</a>您会发现这是最简单的,它将csv文件读取为字典行,其中键对应于每行的列标签。然后,给定要为其选择的键和值对的字典,下面的代码将返回一个适合您需要的字典数组。如果您想去掉键值对,只需要值的数组<a href="https://stackoverflow.com/questions/18453566/python-dictionary-get-list-of-values-for-list-of-keys">this is trivially implemented</a>。因为您可以将csv文件转换为字典列表,所以这就变成了<a href="https://stackoverflow.com/a/25711744/2036035">selecting a dictionary from an array with certain values for keys</a>的问题</p>
<pre><code>import csv
def dict_has_key_values(dict, dict_key_values):
for key in dict_key_values:
if not(key in dict and dict[key] == dict_key_values[key]):
return False
return True
def select_from_dict(csv_dict_reader, dict_key_values):
list_of_dict = []
for row_dict in csv_dict_reader:
if dict_has_key_values(dict, dict_key_values):
list_of_dict.append(dict)
return list_of_dict
with open('yourfile.csv') as csvfile:
selected_key_values = {...}
reader = csv.DictReader(csvfile)
selected_rows = select_from_dict(reader, selected_key_values)
</code></pre>
<p>选定的行现在应该具有</p>
<p>A:至少每个键都在所选的\键\值中,并且</p>
<p>B:与这些键相关的值是相同的。你知道吗</p>