You're thinking to complicated.
Your structure is following:
EVENT_FRAME = [int, str, str, int, int, List[float]]
The last element is already a nested list, unpacking nested lists is easy with
Example code: If you're working on linux:
You can use this also with
What you need to investigate is:
Your structure is following:
EVENT_FRAME = [int, str, str, int, int, List[float]]
The last element is already a nested list, unpacking nested lists is easy with
itertools.chain.fromiterable
Example code: If you're working on linux:
# save data in a file, to test the reading echo "[(10, ['cp5'], ['ERROR'], 201905021800.0, 201905021900.0, [[1.2], [1.5]]), (11, ['cp3'], ['ERROR'], 201905021800.0, 201905021900.0, [[1.2], [1.5]]), (12, ['cp7', 'cp4'], ['ERROR'], 201905021800.0, 201905021900.0, [[1.2], [1.5]])]" > nvm.txt# now use the script to read and evaluate the data in the file
python nvm.py nvm.txtOutput: To test, if the format is ok, you can use json.tool
python nvm.py nvm.txt | python -m json.toolYou can see a big difference in indentation. This is because the tool uses by default indent=4
You can use this also with
json.dumps(your_object, indent=4)
What you need to investigate is:
- for-loops, iteration over nested datatypes:
data = [(1,2),(3,4),(5,6)] for row in data: print(row) # to see what happens
- Argument unpacking:
data = [(1,2),(3,4),(5,6)] one, two, three = data # is very strict, wrong number of elements -> ValueError
- Argument unpacking with *:
data = [(1,2),(3,4),(5,6)] first_element1, *rest = data *elements, last_element1 = data first_element2, *between, last_element2 = data
Everything with a star in front, is a list and consumes as much as it can do without an Exception.
- Sometimes you have the bad situation of nested results, but if you need each of them in one variable, you can use nested argument unpacking:
silly_sequence = ['ok', (200, 'GET'), 'foo'] # now we want to unpack all of them ok, (status, get), foo = silly_sequence
- itertools.chain.fromiterable is used to flatten an iteable:
data = [[1,2,3], [4,5,6], [7,8,9],[10,11,12]] flatten = list(itertools.chain.fromiterable(data)
- (nested) (star) argument unpacking works also in a for-loop:
positions = [(1,4,2), (3,2,1), (4,5,3)] for x, y, z in positions: print(x, y, z) # if you have nested iterables and know you have minimum one element or more, you can use # the star unpacking minium_length_1 = [(1,2,3,4,5,6), (16,1), [1,1.3], [1]] for first, *rest in minium_length_1: print(first, rest) # this will fail, if there is a non-iterable element or an empty sequence
- Generators are good, if you have a process chain. For example parsing data line by line,
next generator parses the line and so on. With generators you can also process memory efficient infinite sequences.
Introduction to Python Generators
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!