简体   繁体   中英

extend two lists and take median in one line

I'm trying to take the median of two concatenated lists, where one of the lists is the result of the numpy repeat function.

This code works fine:

from numpy import median, repeat
g = [4, 5, 6]
g.extend([i.item() for i in repeat(0, 10)])
median(g)

For some reason the above code fails if I try to do this in one line:

g = [4, 5, 6]
median(g.extend([i.item() for i in repeat(0, 10)]))
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

I really need to do this in one line. I tried using asarray but get the same error:

from numpy import asarray
g = [4, 5, 6]
median(asarray(g.extend([i.item() for i in repeat(0, 10)])))

Above, I use item() to convert the numpy type output of repeat back to regular python types.

Because g.extend() returns None , and not the extended list, you can use the + operator between lists instead:

>>> median(g + ([i.item() for i in repeat(0, 10)]))
0.0
# or, getting rid of the unnecessary list comprehension as per @xdhmoore's comment:
>>> median(g + repeat(0, 10).tolist())

Adding two lists together with + functionally does the same as .extend() , but not in place:

>>> g + ([i.item() for i in repeat(0, 10)])
[4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


# vs:

>>> g = [4, 5, 6]

>>> g.extend([i.item() for i in repeat(0, 10)])

>>> g
[4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM