在python中更正列表中的某些公共值
下面是一个示例csv文件:在python中更正列表中的某些公共值,python,excel,csv,Python,Excel,Csv,下面是一个示例csv文件: out_gate,in_gate,n_con /a_a,b,1 /a_a,b,3 /a_b,a,2 /a_b,c,4 /a_c,a,5 /a_c,b,5 /b_c,a,4 /b_d,c,2 import csv def from_csv_to_dict(): reader = csv.DictReader(open(CSV_FILE_NAME)) #the file result = {} # will be the dict to retrun
out_gate,in_gate,n_con
/a_a,b,1
/a_a,b,3
/a_b,a,2
/a_b,c,4
/a_c,a,5
/a_c,b,5
/b_c,a,4
/b_d,c,2
import csv
def from_csv_to_dict():
reader = csv.DictReader(open(CSV_FILE_NAME)) #the file
result = {} # will be the dict to retrun
for row in reader:
key = row.pop("the id column") # "out_gate" in your case
result[key] = row
return result
从这个文件的第一列的out_gate值中,我只想过滤掉那些以“/a_”开头的值,然后删除它们的“/a_”前缀,这样我就剩下一个新的csvfile:(假设实际有30多行)
我怎样才能做到这一点 您可以使用以下代码从csv文件中生成字典:
out_gate,in_gate,n_con
/a_a,b,1
/a_a,b,3
/a_b,a,2
/a_b,c,4
/a_c,a,5
/a_c,b,5
/b_c,a,4
/b_d,c,2
import csv
def from_csv_to_dict():
reader = csv.DictReader(open(CSV_FILE_NAME)) #the file
result = {} # will be the dict to retrun
for row in reader:
key = row.pop("the id column") # "out_gate" in your case
result[key] = row
return result
运行它并查看结果字典,在将文件加载到字典中之后,使用csv文件执行您想要执行的操作会容易得多
编辑:
这是此函数将在文件中返回的结果字典:
{'/b_c': {'in_gate': 'a', 'n_con': '4'}, '/a_a': {'in_gate': 'b', 'n_con': '3'}, '/b_d': {'in_gate': 'c', 'n_con': '2'}, '/a_c': {'in_gate': 'b', 'n_con': '5'}, '/a_b': {'in_gate': 'c', 'n_con': '4'}}
以下是简单的方法:
from csv import reader, writer
lines = []
csv_reader = reader(open(INPUT_CSV_FILE, 'r'))
for i, line in enumerate(csv_reader):
if i == 0:
lines.append(line)
continue
if not line[0].startswith('/a_'):
continue
lines.append([line[0][3:], line[1], line[2]])
csv_writer = writer(open(OUTPUT_CSV_FILE, 'w'))
for l in lines:
csv_writer.writerow(l)
这是一份模棱两可的意向声明。你的问题是什么?您尝试过什么?您的困难是什么?我成功地整理出以“/a”开头的值,但仍坚持整理删除字母“/a”并生成新的csv文件。请在原始帖子中将您现有的代码显示为编辑。您使用csv模块编写csv,与读取csv模块相同,至于删除关于列表理解的阅读,我只是想知道是否存在任何函数来更正列表的整个值的公共值