Home > Blockchain >  Save List of Lists in a file
Save List of Lists in a file

Time:11-01

I want to know if there is a simple way to save list of lists in a file to import it later again like the same list of lists. No matter the size of it.

List_lists=[["a",1,2,3,4],["b",1,2,3,4],["c",1,2,3,4],.....]

Also i want to know is there is a way to throw a list with the first element in each list (in this case "a", "b"). Giving as a result:

first_column=[["a","b","c",......]

Thanks for all the help.

CodePudding user response:

You can save the list into a CSV file using the numpy module in python. Please see sample code below.

code:

import numpy as np

List_lists=[["a",1,2,3,4],["b",1,2,3,4],["c",1,2,3,4]]

# using the savetxt 
# from the numpy module
np.savetxt("list.csv", List_lists, delimiter =", ", fmt ='% s')

output CSV file:

enter image description here

You can use list comprehension to iterate and obtain the first element of the list. Please sample code below

code:

List_lists=[["a",1,2,3,4],["b",1,2,3,4],["c",1,2,3,4]]
res = [item[0] for item in List_lists]
res

output:

enter image description here

Reading the CSV file:

import csv

with open('list.csv', newline='') as f:
    read = csv.reader(f)
    data = list(read)

print(data)

Output:

enter image description here

References:

Saving list to CSV file

List comprehension

Reading CSV file

CodePudding user response:

You could use the zip() function, which joins lists together in their corresponding order.

l1 = ['a', 1, 2, 3, 4]
l2 = ['b', 1, 2, 3, 4]
l3 = ['c', 1, 2, 3, 4]

# To access them through a for loop:
for a, b, c in zip(l1, l2, l3):
    # Do something

Note that using nested lists are fine as well.

  • Related