简体   繁体   中英

How do I write a collection of arrays to csv file in python?

I have a Counter collection in python that looks like

C = [
  ('a', [10, 15]),
  ('b', [20, 23]),
  ('c', [11, 55])
  ...
]

I want to write this collection into a csv delimited file that looks like

letter    property1    property2
a         10           15
b         20           23
c         11           55

I have looked around in stack overflow, most people are trying to only output a dictionary to csv one row at a time. This probably doesn't apply to me. What should I do with my case?

You can create a new list of lists that concatenates the second element of your lists to a list containing the first element of your list. Then you can just use the csv.writer and writerows() methods to write those lists to the file.

import csv
D = [ [x[0]] + x[1] for x in C ]
with open(filename, 'w') as f:
    writer = csv.writer(f)
    writer.writerows(D)

The line D = [ [x[0]] + x[1] for x in C ] can use some explaining.

[x[0]] puts the first element of the element of C into its own list and then + x[1] takes the second element of your list and adds it to the end of the list we just created. So for the first element in your example ('a', [10, 15]) : [x[0]] is the list containing the string 'a' or ['a'] . x[1] is the list [10, 15] . The + operator concatenates lists. So if we concatenate ['a'] + [10, 15] we get ['a', 10, 15] which will write to the csv as you asked for.

import re
c = [
  ('a', [10, 15]),
  ('b', [20, 23]),
  ('c', [11, 55])
]

regex = r"\('(\w)', \[(\d+), (\d+)\]\)"
for x in re.findall(regex ,str(c)):
    print ','.join(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM