[英]Python CSV to extract and time values from element
我编写了一个python脚本,将pgRouting(在PostgreSQL中)的输出存储在CSV文件中,并且CSV文件的代码和部分看起来像这样,
import sys, os
os.chdir('C:\Users\Heinz\Desktop')
print os.getcwd()
#set up psycopg2 environment
import psycopg2
#driving_distance module
query = """
select *
from shortest_path ($$
select
gid as id,
source::int4 as source,
target::int4 as target,
pi::double precision as cost,
pi_rcost::double precision as reverse_cost
from network
$$, %s, %s, %s, %s
)
"""
#make connection between python and postgresql
conn = psycopg2.connect("dbname = 'TC_area' user = 'postgres' host = 'localhost' password = 'xxxx'")
cur = conn.cursor()
#count rows in the table
cur.execute("select count(*) from network")
result = cur.fetchone()
k = result[0] + 1 #number of points = number of segments + 1
#run loops
#import csv module
import csv
import tempfile
import shutil
rs = []
i = 1
l = 1
filename = 'test.csv'
with open(filename, 'wb') as f:
while i <= k:
while l <= k:
cur.execute(query, (i, l, False, True))
rs.append(cur.fetchall())
element = list(rs)
writer = csv.writer(f, delimiter = ',')
writer.writerow(element)
rs = []
l = l + 1
l = 1
i = i + 1
conn.close()
现在我想做三件事,
如何做到?我可以一步一步完成这项任务吗?
我正在Windows 8.1 x64下使用python 2.7.4和PostgreSQL 8.4。
UPDATE#1我在脚本中添加了以下两行(谢谢,shaktimaan),
[a[-1] for a in element]
product = reduce(lambda x,y: x * y, [a[-1] for a in element])
这是输出的一部分,
本质上,您只需要知道如何对列表中的所有元素进行多重处理。 可以使用reduce()
方法来完成:
reduce(lambda x,y: x * y, a_list)
现在,查看您的代码,您的csv中的每个条目都是由以下语句生成的:
element = list(rs)
例如, element
可以具有以下内容:
[(1, -1, 0.0), (1, 1, 0.844), (2, -1, 0)]
您需要将每个内部元组的第三个数字相乘。 因此,快速创建一个列表,以提取每个子元组的第三个元素
[a[-1] for a in element]
现在,将其插入之前的reduce()
:
product = reduce(lambda x,y: x * y, [a[-1] for a in element])
对于上面的示例,此命令打印为0.0
。 现在您已经拥有了该产品,可以将其用作以及如何在输出CSV中打印它。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.