-1

I was looking up a way to find pixels values over the three channel of a segmentation class image to replace them with their categories,and i found this code which works fine, but i have trouble understanding what the * operator is used for exactly, my understanding is that it simply unpack lists and dictionary in order,but why doesnt it work without it. Only thing i can see is that the problem comes from the limited number of argument on np.logical_and, but why does unpacking sunddendly makes it work. So yeah if anyone has some intuition i'd apreciate it, here is the code from the link:

>>> pixel_class_dict = {1: [18, 19, 20], 2: [9,10,11]}
>>> a = np.arange(2*4*3).reshape(2,4,3)
>>> b = np.zeros((a.shape[:2]), dtype=np.int)
>>> for pixel_class, pixel_values in pixel_class_dict.items():
        #here is the line i have trouble with
...     mask = np.logical_and(*(a[..., channel] == pixel_values[channel] 
...       for channel in range(a.shape[-1])))
...     b += pixel_class*mask 
  • `*` spreads (splashes) the values from the iterable so they become separate arguments to the function call. Without it, you would pass a single argument: the iterator. – trincot Oct 08 '21 at 13:11
  • 2
    Does this answer your question? [What does the star and doublestar operator mean in a function call?](https://stackoverflow.com/questions/2921847/what-does-the-star-and-doublestar-operator-mean-in-a-function-call) – Alan Bagel Oct 08 '21 at 13:11
  • note that in this case the generator expression might be better written on the line before, and then unpacked. Currently it's not the *most* readable – 2e0byo Oct 08 '21 at 13:21

1 Answers1

1

Simply put, in the case you have a function:

def myFunction(parameter1,parameter2,parameter3):
   ...

if you provide a list such as

variable = [25,30,35]

and want to use it for the function, if you do this:

myFunction(variable)

then, parameter1 will have the value: [25,30,35], basically its the same if you did this:

myFunction([25,30,35],None,None)

if you want to split the variables correctly, you use the * operator as follows:

myFunction(*variable)

which is the same as:

myFunction(25,30,35)

A simple example to explain further:

print([1,2,3,"test"])
print(*[1,2,3,"test"])

Output:

[1, 2, 3, '4444mate']
1 2 3 4444mate
> 
Zaid Al Shattle
  • 1,454
  • 1
  • 12
  • 21