Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python take modified list outside for loop

I have been working on a way to make list of tuples and finding the average of each tuples.

myList = [(1,2,3),(4,12,6)]
def GS(myList):
     for miniList in myList:
          r = miniList[0]
          g = miniList[1]
          b = miniList[2]
          GS = round((r+g+b)/3,2)
          miniList = list(miniList)
          miniList[0] = GS
          miniList[1] = GS
          miniList[2] = GS
          miniList = tuple(miniList)
     return myList     

 print(GS(myList))

my list is [(1,2,3),(4,12,6)]

I should get the average of each tuple and replace the three

output : [(2.0,2.0,2.0),(7.33,7.33,7.33)]

like image 442
Charan Vengatesh Avatar asked May 22 '26 22:05

Charan Vengatesh


2 Answers

You can use a list comprehension. Below is an example which avoids calculating the length of each tuple twice via map and zip iterators.

myList = [(1,2,3),(4,12,6)]

def GS(L):
    lens = map(len, L)
    res = [(sum(i)/i_len,)*i_len for i, i_len in zip(L, lens)]
    return res

print(GS(myList))

[(2.0, 2.0, 2.0), (7.333333333333333, 7.333333333333333, 7.333333333333333)]

If you wish to round decimals, you can use:

res = [(round(sum(i)/i_len, 2),)*i_len for i, i_len in zip(L, lens)]
like image 146
jpp Avatar answered May 25 '26 17:05

jpp


myList = [(1,2,3),(4,12,6)]
[(round(sum(e)/len(e)),)*len(e) for e in myList]
# [(2.0, 2.0, 2.0), (7.33, 7.33, 7.33)]
like image 37
Sunitha Avatar answered May 25 '26 15:05

Sunitha