Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zipped array returns as <zip object at 0x02B6F198>

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.

like image 758
callumbous Avatar asked Nov 08 '15 11:11

callumbous


People also ask

What does zip (*) do in Python?

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.

Can we zip tuple in Python?

Python zip() The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.

How do I get a list from zip object?

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.


1 Answers

If you are trying to print the zipped lists directly then that won't work. zipreturns 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')]
like image 74
Steven Summers Avatar answered Sep 19 '22 03:09

Steven Summers