Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - zip only lists that contain data

I have a script that converts data from one type to another. The source file can have one, two or all of: position, rotation and scale data.

My script zips the 3 together after conversions have taken place for the output file.

In this case, my source file only contains position data. So the lists returned at the end are:

pData = [['-300.2', '600.5'],['150.12', '280.7'],['19.19', '286.56']]
rData = []
sData = []

translationData = list(zip(pData, rData, sData))

If I try this, it will return [] because the shortest list is []. If I try:

translationData = list(zip_longest(pData, rData, sData))

I get:

`[(['-300.2', '600.5'], None, None), (['150.12', '280.7'], None, None), (['19.19', '286.56'], None, None)]`

Is there any way to only zip lists that contain data, or remove the None's from within the tuples within the list?

Thanks in advance!

like image 607
Tom Tatchell Avatar asked Nov 03 '25 08:11

Tom Tatchell


1 Answers

You can use the filter builtin embedded in a list-comp.

Note: In Python 3 filter returns an iterator, so you will need to call tuple() on it. (unlike in py2)

pData = [['-300.2', '600.5'],['150.12', '280.7'],['19.19', '286.56']]
rData = []
sData = []

from itertools import zip_longest  # izip_longest for python 2
[tuple(filter(None, col)) for col in zip_longest(pData, rData, sData)]

Result:

[(['-300.2', '600.5'],), (['150.12', '280.7'],), (['19.19', '286.56'],)]
like image 179
Inbar Rose Avatar answered Nov 04 '25 21:11

Inbar Rose