Reputation: 542
How would I print each list in list1 or list2 as a column without the '[ ]' included?
import csv
def test():
list1 = [[1, 2, 3, 4], [3, 2, 5], [9, 3, 6, 8, 4]]
list2 = [[2, 2, 4, 4], [1, 9, 10], [2, 7, 7, 4, 5]]
with open('doc.csv', 'w', newline='') as file:
writer = csv.writer(file, quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(list1)
writer.writerow(list2)
if __name__ == '__main__':
test()
This is close to what I desire but has [ ] in the string:
[1, 2, 3, 4],[3, 2, 5],[9, 3, 6, 8, 4]
[2, 2, 4, 4],[1, 9, 10],[2, 7, 7, 4, 5]
EDIT:
I want:
"1, 2, 3, 4","3, 2, 5","9, 3, 6, 8, 4"
"2, 2, 4, 4","1, 9, 10","2, 7, 7, 4, 5"
Upvotes: 2
Views: 439
Reputation: 123393
This is how I'd do it:
import csv
def nested_list_formatter(nested):
return tuple(','.join(str(item) for item in sublist) for sublist in nested)
def test():
list1 = [[1, 2, 3, 4], [3, 2, 5], [9, 3, 6, 8, 4]]
list2 = [[2, 2, 4, 4], [1, 9, 10], [2, 7, 7, 4, 5]]
with open('doc.csv', 'w', newline='') as file:
writer = csv.writer(file, quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(nested_list_formatter(list1))
writer.writerow(nested_list_formatter(list2))
if __name__ == '__main__':
test()
Resulting contents ofdoc.csv
:
"1,2,3,4","3,2,5","9,3,6,8,4"
"2,2,4,4","1,9,10","2,7,7,4,5"
Upvotes: 2
Reputation: 365597
A column is just printed by calling str
on it. So, if you want to do something else, you have to convert each column into a string yourself* (since calling str
on a string just returns the string).
In your case, we have to turn every element of the outer list into strings in the format we want… which will itself require turning every element of each inner list into strings so we can join them up in some way. In general, in Python, to do something to every element of a sequence, you either call map
, or you write a comprehension, so I'll do one of each.
After your edits, it looks like you want comma-separated columns, and comma-space-separated values within the columns, but that's OK because you want the columns auto-quoted. That's easy.
To join up the values with ', '
, you just call ', '.join()
on them.
def stringify_column_list(column_list):
return ', '.join(str(value) for value in column_list)
The weird separator and quoting, you already know how to handle in the writer
. So the only thing left is to call our formatting function on each column:
writer.writerow(map(stringify_column_list, list1))
writer.writerow(map(stringify_column_list, list2))
You might even want to consider using the csv
module again to create the column values. But this is probably overkill here.
* Or into some other object with a __str__
method that does what you want, but that's rarely worth doing.
Upvotes: 1