简体   繁体   中英

How to elegantly "min" and then perform an operation with the reference in python

Suppose you have two lists nums1 and nums2 , and you want to check which of the two lists first elements is smaller, remove it and then move that into an accumulator list which you return.

You might accomplish it using the following code:

def stackoverflowmethod(nums1, nums2):
    accumulator = [] 
    # determine if nums1[0] or nums2[0] is smaller and then remove it
    if nums1[0] <= nums2[0]:
        accumulator.append(nums1.pop(0))
    else:
        accumulator.append(nums2.pop(0))
    return accumulator

However this might look very unsightly in that you would rather have written something like

def idealMethod(nums1, nums2):
    accumulator.append(RemoveFromTheFrontOfOYourList(min(nums1[0], nums2[0])))
    return accumulator

The only thing that makes this hard is the mysterious method RemoveFromTheFrontOfOYourList needs to be able to figure out which list an item came from after the min operation was conducted on it,

IE if we had a slightly less forgetful min function then something elegant could be done here.

If stylistically what I'm asking for makes sense, how does one accomplish it in python 3?

Use min on the lists , with operator.itemgetter(0) as the key function.

import operator

smaller_0 = min(nums1, nums2, key=operator.itemgetter(0))
accumulator.append(smaller_0.pop(0))

operator.itemgetter(0) is the same as lambda x: x[0] for this purpose.


Or use a ternary that gets the list with a smaller item 0, then pop from it

smaller_0 = nums1 if nums1[0] <= nums2[0] else nums2
accumulator.append(smaller_0.pop(0))

This is like Michael's answer , but a bit DRYer

使用三元语句:

acc.append(nums1.pop(0)) if nums1[0] < nums2[0] else acc.append(nums2.pop(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