在不同行上列出csv文件的列表索引

2024-10-04 05:25:02 发布

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

写入csv时,是否可以将列表中的每个索引拆分到新行?你知道吗

例如,我向一个列表添加了许多索引,当我写入csv时,它们都打印在同一行上。你知道吗

输出电流路由.append当我写入csv文件时。。。你知道吗

("Index1")("Index2")("Index3")("Index4")("Index5")("Index6")

我想写为:

("Index1")
("Index2")
("Index3")
("Index4")
("Index5")
("Index6")

我知道我会写作

rec=index[1]
f.writerow(rec)

重复6次。。问题是,我的列表中可以有2个索引到100个索引,所以我需要做的是能够根据列表中索引的数量打印n个索引。你知道吗

谢谢。
f=打开(“route1.csv”,“w”) f、 截断() f、 关闭()

print "Route Calculator"
cur = (0, 0)
route = [0]
xy = [ ]
z= ()
zz= []
dest=[]
n = input("Enter number of destinations to visit:")
a = range(1, n + 1)
cidd = []
for i in range(n):
    cid=raw_input("Enter Customer ID")
    f3=csv.reader(open("data/customer.csv",'r'))
    for row in f3:
        if row[0]==cid:
            street=row[2]
            pcode=row[3]
            tel=row[4]
            x=eval(row[5])
            y=eval(row[6])
            z=row[1]
            xy.append((x,y))
            zz.append(((cid,z)))
            cidd.append((((cid,z,street,pcode,tel))))

print "Destinations:",cidd
dest = [ ]
ndd =[ ]
for i in range(n):
    nd = []
    for i in xy:
        i = list(i)
        distance = round(math.hypot((cur[0] - i[0]), (cur[1] - i[1])),4)
        nd.append(distance)

    print "Current location:", cur
    print "Coordinates to travel to:", xy
    print "Distances to destinations:", nd, "minimum distance:", min(nd)
    nn = (xy[nd.index(min(nd))][0], xy[nd.index(min(nd))][1])
    print "Nearest neighbour:", nn
    print "Nearest destination:", cidd[xy.index(nn)]
    print
    dest.append(((min(nd))))
    ndd=sum(dest)
    route.append(((cidd[xy.index(nn)],(min(nd)))))
    del cidd[xy.index(nn)]
    xy.remove(nn)
    cur = list(nn)

distance = round(math.hypot(nn[0], nn[1]), 4)
dest.append(distance)
route.append(0)
cidd.extend(dest)
print "Destination List:",route
o=open("route1.csv",'ab')
f=csv.writer(o)
rec3=("Driver:",driver)
f.writerow(rec3)
rec4=("Date:",(time.strftime("%d/%m/%Y")))
f.writerow(rec4)
header=(["CID..","Customer Name..........","Address.........","Postcode..","Telephone..","Distance from prev"])
f.writerow(header)
rec=(route)
f.writerow(rec)
rectotal=("Total Distance to Travel",ndd)
f.writerow(rectotal)
print "Route Saved to route1.csv"

这是我当前的代码和路由.append我试着索引到不同的行上。谢谢


Tags: csvtoindexnnroutedestrowdistance
2条回答

只需使用writerows函数。你知道吗

示例:

f.writerows(["a","b","c"])

将输出

a
b
c

假设以下工作

rec=(route[1],)
f.writerow(rec)

您可以使用for循环来避免多次写入。你知道吗

for i in xrange(len(index)):
    rec=(route[i],) 
    f.writerow(rec)

相关问题 更多 >