Pregunta

I have two lists, when I print them separately using:

writer.writerows(list_)

I get

list_1:

0   -0.00042    0.004813    0.010428    0.051006
1   0.000053    0.004531    0.010447    0.051962
2   0.000589    0.004518    0.009801    0.052226
3   0.000083    0.004581    0.010362    0.052288
4   -0.000192   0.003726    0.011258    0.051094
5   0.000281    0.004078    0.01008     0.052156

list_2:

-0.000419554    -0.000366128    0.000223134     0.000306416     0.000114709

It's been a whole day I've been trying to add list_2 as another column to list_1 and write them to a csv file. I thought it was straightforward but have stuck. I appreciate any help.

¿Fue útil?

Solución 2

Here is an example, not knowing what your data look like, so I have to guess:

list_1 = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
]
list_2 = [10,20,30]

list_1 = [row + [col] for row, col in zip(list_1, list_2)]
for row in list_1:
    print row

Output:

[1, 2, 3, 10]
[4, 5, 6, 20]
[7, 8, 9, 30]

Now that list_1 has list_2 as a new column, you can use the csv module to write it out.

Otros consejos

A general solution which combines columns from two lists of lists (or other iterables):

import csv
import itertools
import sys

def combine_columns(iterable1, iterable2):
    for x, y in itertools.izip(iterable1, iterable2):
        yield list(x) + list(y)

list1 = [[11, 12, 13], [21, 22, 23]]
list2 = [[14, 15], [24, 25]]
writer = csv.writer(sys.stdout)
writer.writerows(combine_columns(list1, list2))

Output:

11,12,13,14,15
21,22,23,24,25
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top