简体   繁体   中英

Converting a list of lists into a multi-dimensional list in python

I have manipulated a dataset into looking something like this:

# data_dict = { 'epoch':[[int(n), int(m), int(c + cs), int(s + ss)], ...], ... }

where every key ( 'epoch' ) is associated with a list of lists that look something like this:

# [1, 0, (c + cs)_10, (s + ss)_10]
# [2, 0, (c + cs)_20, (s + ss)_20]
# [3, 0, ...]
# [4, 0, ...]
# [5, 0, ...]
# [1, 1, ...]
# [1, 2, ...]
# [1, 3, ...]
# [1, 4, ...]
# [1, 5, ...]
#    .
#    .
#    .
# [5, 5, (c + cs)_55, (s + ss)_55]

What I want is to be able to access any value of (c + cs)_mn given an 'epoch' and values for m and n .

My initial thought is to somehow convert each list of lists into a multidimensional list, so I would be able to see the values I want by calling data_dict['epoch'][m][n] . Is it possible to do this?

Going further, is it even feasible to do this? The raw data is FORTRAN-formatted, but I know nothing about FORTRAN. As a result, I have taken this (admittedly convoluted) approach to converting the data into something easily readable.

For reference, the data I am looking at can be found here .

Based on how your data looks now the brute force would just be

for item in your_list:
   if item[0] == m and item[1] == m:
       return item[2]

Given how your data is structured now you can do the following

new_dict = {}
for row in data_dict['epoch']:
    if new_dict.get(row[0]):
        new_dict[row[0]].update({row[1]:row[2]})
    else:
        new_dict[row[0]] = {row[1]:row[2]}
return_data = {'epoch':new_dict}
d = {}
for v in data_dict['epoch']:
    d.setdefault(v[0], {})[v[1]] = v[2]

Or using Python's built-in defaultdict you can easily get it

from collections import defaultdict
def tree(): return defaultdict(tree)
d = tree()
for v in data_dict['epoch']: d[v[0]][v[1]] = v[2]

data_dict = {'epoch':d}

you can calling data_dict['epoch'][m][n] to get value.

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