Home > Software design >  Re-organizing lists of lists in python
Re-organizing lists of lists in python

Time:01-11

I am new to python and trying to read a large file with position data for objects over a time series. Something like:

for a in dum_un.file:
    
    FD = dum_un.select_object("type 1")
    r = FD.positions

Each r corresponds to a specific time point, and each list-within-the-list corresponds to the x, y, and z positions of an object at that time point. The ordering is the same throughout the time series. Example for 2 objects:

First iteration of the for loop: r = [[1.11, 2.64, 3.3],[4.0, 5.12, 6.32]]

Second iteration of the for loop: r = [[5.7, 4.44, 1.8],[6.3, 8.9, 4.7]]

I want to be able to access a list of all x (or y or z) values for each object over the entire time series, e.g., here:

x = [1.11, 5.7] for object 1

x = [4.0, 6.3] for object 2

CodePudding user response:

Here's one way.

The parsing creates a dictionary called objects that looks something like this:

{
  "1": {
    "x": [1.11, 5.7],
    "y": [...],
    "z": [...],
  },
  "2": {
    "x": [...],
    "y": [...],
    "z": [...],
  },
  ...
}

Here's the code:

# This list represents the value of `r` in each iteration
all_r = [
    [[1.11, 2.64, 3.3],[4.0, 5.12, 6.32]],
    [[5.7, 4.44, 1.8],[6.3, 8.9, 4.7]]
]

# Initialise a dictionary to collect all the results
# The key for each entry will be the object "ID"
# e.g. the first item in `r` represents "object 1".
objects = dict()

for r in all_r:
    for i, coordinates in enumerate(r):
        # Python indexes start at zero. So increment by one to match your definition
        object_id = str(i   1)
    
        # Initialise the dictionary key for our object if it doesn't exist already
        if object_id not in objects.keys():
            objects[object_id] = {
                "x": [],
                "y": [],
                "z": [],
            }

        # Add each co-ordinate to their relevant X, Y or Z list
        objects[object_id]["x"].append(coordinates[0])
        objects[object_id]["y"].append(coordinates[1])
        objects[object_id]["z"].append(coordinates[2])

expected_x_object_1 = [1.11, 5.7]
expected_x_object_2 = [4.0, 6.3]

actual_x_object_1 = objects.get("1", dict()).get("x", None)
actual_x_object_2 = objects.get("2", dict()).get("x", None)

assert expected_x_object_1 == actual_x_object_1
assert expected_x_object_2 == actual_x_object_2
  • Related