开发者

How to condense this function?

def average(tup):
  """ ugiufh """
   total = ((int(tup[0]) + int(tup[1]) + int(tup[2]))/3,
            (int(tup[0]) + int(tup[1]) + int(tup[2]))/3,
            (int(tup[0]) + int(tup[1]) + int(tup[2]))/3)
   return total

I am writing a function to average out three element in a tuple which means if the original tuple = (1, 2, 3) which give me tuple = (2, 2, 2)

My question is the开发者_JAVA技巧re any way to condense what wrote to give me the same answer? If yes, how to condense it?

Thanks


If you are sure you want integer division, you can use

def average(tup):
    n = len(tup)
    return (sum(int(x) for x in tup) / n,) * n


There are ways to condense the code you listed, but what you should really strive for is making the code more readable.

def average(a):
    """Return a tuple where every element of ``a`` is replaced by the average of the values of ``a``."""
    length = len(a)
    average = sum(a) / length
    return (average,) * length # A 1-tuple containing the average, repeated length times

This has the added benefit of being able to accept tuples of any input length.

One change that was made in this version of the code is that the elements of the tuple are not first coerced to integers. Unless there is some specialised reason why you need this, you should probably separate that logic out into a separate bit of code.

data = (1, '2', 3.0)
normalised_data = (int(x) for x in data) # A generator expression that yields integer-coerced elements of data
result = average(normalised_data)

Of course, if you insist on a condensed answer, Sven's answer is functionally equivalent to mine.


def average(tup):
    def mean(t):
        return sum(t, .0) / len(t)
    return (mean(tup),) * len(tup)

One line:

def average(tup): return ((lambda t: sum(t, .0) / len(t))(tup),) * len(tup)

or

average = lambda tup: ((lambda t: sum(t, .0) / len(t))(tup),) * len(tup)

But the first piece of code is better than these.


def average(tup):
    return (sum(tup) / len(tup),) * len(tup)


def average(tup):
    """ ugiufh """
    el = sum( map(int,tup) )/3
    return (el,el,el)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜