拆分列表和值

时间:2013-07-24 08:17:25

标签: python csv python-2.7 split

在python脚本中,我有2个浮动值和2个列表,我想在csv文件中写入。 lonwgs84和latwgs84是浮点值,col1和col2是列表。当我用:

编写csv文件时
with open(ausgabe, "wb") as f:  
    datawriter = csv.writer(f)
    for each in zip(lonwgs84 , latwgs84, col1s, col2s):
        cols = each[0] , each[1], each[2] + each[3]
        datawriter.writerow(cols)

我得到以下输出:

51.821336803,11.6756790532,"['~11:16:05.833', '$GPGGA', '091607.00', '5149.28020818', 'N', '01140.54074319', 'E', '', '', '000.01']"

但我需要的是:

51.821336803,11.6756790532,~11:16:05.833,$GPGGA,091607.00,5149.28020818,N,01140.54074319,E,,,000.01

我尝试使用split,但这似乎只适用于字符串。也许有人知道如何做到这一点?非常感谢!

1 个答案:

答案 0 :(得分:0)

只需将行切片以获得前2个元素,连接第3个和第4个元素:

datawriter.writerow(each[:2] + each[3] + each[4])

或者,首先解包元素:

for fp1, fp2, lst1, lst2 in zip(lonwgs84 , latwgs84, col1s, col2s):
    datawriter.writerow([fp1, fp2] + lst1 + lst2)

演示:

>>> [fp1, fp2] + lst1 + lst2
[51.821336803, 11.6756790532, '~11:16:05.833', '$GPGGA', '091607.00', '5149.28020818', 'N', '01140.54074319', 'E', '', '', '000.01']

你创建了前两个元素的元组,加上后两个元素连接+

cols = each[0], each[1], each[2] + each[3]

导致(each[0], each[1], [elements of each[2] and each[3]])的嵌套结构。