I have two arrays: X = [1,2,3,4,5,3,8]
and Y = ['S', 'S', 'S', 'S', 'S', 'C', 'C']
. when i print the zipped array of this, it produces <zip object at 0x02B6F198>
. The reason these two arrays are zipped is so I can sort Y
corresponding to sorted(X)
in the line
sortedY = [y for x,y in sorted(zip(X,Y))]
This line of code doesn't sort Y how I would want (sortedY = ['S','S','C','S','S','S','C']
) but SortedX
stays in the same arrangement as X
.
I have a second program in which I use this code and it works fine but this program is significantly smaller in size than the original program.
Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.
Python zip() The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.
Short answer: Per default, the zip() function returns a zip object of tuples. To obtain a list of lists as an output, use the list comprehension statement [list(x) for x in zip(l1, l2)] that converts each tuple to a list and stores the converted lists in a new nested list object.
If you are trying to print the zipped lists directly then that won't work. zip
returns an object and so when you try to print it you just get the object method. If you want to see it as a list, then apply an operation that returns a list.
X = [1,2,3,4,5,3,8]
Y = ['S', 'S', 'S', 'S', 'S', 'C', 'C']
# Some Simple Methods Include
print(list(zip(X, Y)))
print([i for i in zip(X, Y)])
# Output
[(1, 'S'), (2, 'S'), (3, 'S'), (4, 'S'), (5, 'S'), (3, 'C'), (8, 'C')]
Now I'm not sure what the issue was though, as what you provided should be working
sortedY = [y for x,y in sorted(zip(X,Y))]
print(sortedY)
# Output
['S', 'S', 'C', 'S', 'S', 'S', 'C']
As you can see it sorts Y corresponding to sorted X
print(sorted(zip(X,Y)))
#Output (X, Y)
[(1, 'S'), (2, 'S'), (3, 'C'), (3, 'S'), (4, 'S'), (5, 'S'), (8, 'C')]
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