For example, I have these variables
a = [1,2]
b = [3,4]
If I use function zip()
for it, the result will be:
[(1, 3), (2, 4)]
But I have this list:
a = [[1,2], [3,4]]
And, I need to get the same as in the first result: [(1, 3), (2, 4)]
. But, when I do:
zip(a)
I get:
[([1, 2],), ([3, 4],)]
What must I do?
The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
Practical Data Science using PythonUse the zipfile module to create a zip archive of a directory. Walk the directory tree using os. walk and add all the files in it recursively.
One of the way to create Pandas DataFrame is by using zip() function. You can use the lists to create lists of tuples and create a dictionary from it. Then, this dictionary can be used to construct a dataframe. zip() function creates the objects and that can be used to produce single item at a time.
zip
expects multiple iterables, so if you pass a single list of lists as parameter, the sublists are just wrapped into tuples with one element each.
You have to use *
to unpack the list when you pass it to zip
. This way, you effectively pass two lists, instead of one list of lists:
>>> a = [[1,2], [3,4]]
>>> zip(*a)
[(1, 3), (2, 4)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With