Search code examples
pythonmatplotlibtuples

Python: Using zip on a 2-D list slice


I am making a bar graph with very large 2-D lists of data. I had hard coded all the bar plots with the following: bottom=[sum(item) for item in zip(topList[1], topList[2], topList[3], ...)] and it worked well. I then had the thought, could I use a sublist instead? That way I could iteratively create bars, improve the readability, and save (visual) space.

But the following code did not work: bottom=[sum(item) for item in zip(topList[1:])] I got the error that slices are unhashable, I broke it down to see what the difference was between the slice and just listing the sublists, which was that the slice an actual list itself while the listed sublists were not encapsulated in another structure. Is there a simple/efficient way to create a list of tuples from a 2-d list, remove the sublists from the slice and pass them in to zip in a funcitonal manner, or some other solution to my overall goal?


Solution

  • I think you can unpack a tuple or a list into positional arguments using unpacking operator ie star.

    bottom=[sum(item) for item in zip(*topList[1:])]
    

    if topList uses hash key, you can iterate through the hash keys instead

    bottom=[sum(item) for item in zip(*[topList[x] for x in range(1, n)])