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)]
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)]
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With