1

I have a list of lists and need to write each of its elements in csv columns. Using the code below it outputs exactly what I want.

for row in izip_longest(*averages_, fillvalue = ['']):
    writer.writerow(row[0] + row[1])

a sample line of row[0]:

['0.000000', '0.000586', '0.005819', '0.011434', '0.052012', 0.000586118993]

Question: How can I replace the part (row[0] + row[1]) with a code with a variable in it so that it automatically adds any number of sub-lists (row[i] + row[i+1] + row[i+2]...) in the main list?

PyLearner
  • 239
  • 2
  • 5
  • 11

2 Answers2

1

If row is a list of lists, replace (row[0] + row[1]) with

list(itertools.chain.from_iterable(row))

or

[item for sublist in row for item in sublist]

You are flattening a lists of lists. I picked both of those from https://stackoverflow.com/a/952952/2823755

Community
  • 1
  • 1
wwii
  • 23,232
  • 7
  • 37
  • 77
1

If I understand well what you want than the following should do the job :

writer.writerow(reduce(lambda x, y: x+y, row)) 

This work over all elements of row. If you want to sum the first count elements you can try like that :

writer.writerow(reduce(lambda x, y: x+y, row[:count - 1])) 
Andrei Boyanov
  • 2,309
  • 15
  • 18
  • Had not used `lambda` before! seems to be very handy. Thanks for that Andrei. I selected wwii's answer just for slightly less execution time, but yours also works like a charm. – PyLearner Dec 04 '13 at 21:58