Python:如何将list作为参数传递给函数?

2024-05-23 18:01:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚从Python开始,使用以下代码将CSV文件导入到sqlite3表中,我自由地承认我已经从互联网上复制了大部分内容:

with open(getPathTo('my.csv'), 'r') as csvfile:
  reader = csv.DictReader(csvfile)
  records = [(row['SEGMENT'], row['Comp 1'], row['Comp 2']) for row in reader]
c.executemany("INSERT INTO comparison (`SEGMENT`, `Comp 1`, `Comp 2`) VALUES (?,?,?);", records)
conn.commit()

它工作得很好,但是我在很多文件和表中重复这个过程,我想把它转换成一个函数。我的目标是:

^{pr2}$

但是,给定一个columns的列表,如何在这行中使用它:

records = [(row['SEGMENT'], row['Comp 1'], row['Comp 2']) for row in reader]

我想我只是有点被语法搞糊涂了。在


Tags: 文件csvcsvfile代码in内容forsegment
3条回答

所以我想你要问的是,给定一个键(列)列表,我如何从字典中提取它们?我们只需使用内存中的CSV文件来测试:

>>> example_data = """col1,col2,col3\na1,a2,a3\nb1,b2,b3\nc1,c2c3"""
>>> print example_data
col1,col2,col
a1,a2,a3
b1,b2,b3
c1,c2c3

那么,如果我们有一个基于此的CSV导航仪:

^{pr2}$

因此,如果我们想根据字段列表进行迭代:

>>> for row in reader:
...     print 'insert into mytable (%s) values (%s)' % (','.join(reader.fieldnames), ','.join(['?']*len(reader.fieldnames)))
insert into mytable (col1,col2,col3) values (?,?,?)
insert into mytable (col1,col2,col3) values (?,?,?)
insert into mytable (col1,col2,col3) values (?,?,?)

很明显,从那以后,你会想让它适应你的功能。但这是否回答了您关于csvreader和操作Python列表的机制的问题?在

(注意,这是针对python2的。)

也许是这样的?当然没有经过测试。在

def importCSVToTable(conn, filename, table, columns)
    with open(getPathTo(filename), 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        records = []
        for row in reader:
            for col in columns:
                records.append(row[col])
    conn.executemany("INSERT INTO comparison (" + ','.join(columns) + ") VALUES ("+ ','.join(["?"]*columns.length) +");", records)
    conn.commit()

下面是一些示例代码,显示了一些可能有帮助的内容。我们使用带有过滤if语句的嵌套理解,以确保我们不会试图访问不存在的dict项。在

In [3]: def importCSVtoTable(file, table, columns):
   ...:     # 'mock' data to simulate a reader
   ...:     reader = [{'SEGMENT': 2, 'Comp 1': 'dogs'}, {'Comp 2': 'cats', 'OTHERTHING': 4}
   ...:     print [[row[label] for label in columns if label in row] for row in reader]
   ...:

In [4]: importCSVtoTable(None, None, ['SEGMENT', 'Comp 1'])
[[2, 'dogs'], []]

In [5]: importCSVtoTable(None, None, ['SEGMENT', 'Comp 1', 'Comp 2'])
[[2, 'dogs'], ['cats']]

相关问题 更多 >