开发者

How to map a function to a triple nested list and keep the triple nested list intact?

开发者 https://www.devze.com 2023-04-01 17:04 出处:网络
I\'ve have been building an analysis workflow for my PhD and have been using a triple nested list to represent my data structure because I want it to be able to expand to an arbitrary amount of data i

I've have been building an analysis workflow for my PhD and have been using a triple nested list to represent my data structure because I want it to be able to expand to an arbitrary amount of data in its second and third levels. The first level is the whole dataset, the second level is each subject in the dataset and third level is a row for each measure that each subject.

[dataset]
      |
      [subject]
              |
              [measure1, measure2, measure3]

I am trying to map a function to each measure - f开发者_Python百科or instance convert all the points into floats or replace anomalous values with None - and wish to return the whole dataset according to its nesting but my current code:

for subject in dataset:
    for measure in subject:
        map(float, measure)

...the result is correct and exactly what I want but the problem is that I can't think how to assign the result back to the dataset efficiently or without losing a level of the nest. Ideally, I would like it to change the measure *in place but I can't think how to do it.

Could you suggest an efficient and pythonic way of doing that? Is a triple nested list a silly way to organize my data in the program?


Rather than doing it in place, make a new list

 dataset = [[[float(value) for value in measure] 
                           for measure in subject] 
                           for subject in dataset] 


return [[map(float, measure) for measure in subject] for subject in dataset]

You can return a list instead of altering it in place -- this is still remarkably efficient and preserves all the information you want. (aside: In fact, it's often faster than assigning to list indexes [citation needed], which is what others have suggested here!)


A straight-forward way to do that in place would be:

for subject in dataset:
    for measure in subject:
        for i, elem in enumerate(measure):
            measure[i] = float(elem)

Alternatively, use the slice operator to upate the list in-place with the results of map

for subject in dataset:
    for measure in subject:
        measure[:] = map(float, measure)


This should do the job

for subject in dataset:
    for measure in subject:
        for i, m in enumerate(measure):
            measure[i] = float(m)
0

精彩评论

暂无评论...
验证码 换一张
取 消