Is there any pythonic way to find average of specific tuple elements in array?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I want to write this code as pythonic. My real array much bigger than this example.
( 5+10+20+3+2 ) / 5
print(np.mean(array,key=lambda x:x[1]))
TypeError: mean() got an unexpected keyword argument 'key'
array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
sum = 0
for i in range(len(array)):
sum = sum + array[i][1]
average = sum / len(array)
print(average)
import numpy as np
print(np.mean(array,key=lambda x:x[1]))
How can avoid this?
I want to use second example.
python arrays python-3.x tuples average
add a comment |
I want to write this code as pythonic. My real array much bigger than this example.
( 5+10+20+3+2 ) / 5
print(np.mean(array,key=lambda x:x[1]))
TypeError: mean() got an unexpected keyword argument 'key'
array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
sum = 0
for i in range(len(array)):
sum = sum + array[i][1]
average = sum / len(array)
print(average)
import numpy as np
print(np.mean(array,key=lambda x:x[1]))
How can avoid this?
I want to use second example.
python arrays python-3.x tuples average
What version of Python are you using?
– Peter Wood
2 hours ago
1
@PeterWood python 3.7
– Şevval Kahraman
1 hour ago
add a comment |
I want to write this code as pythonic. My real array much bigger than this example.
( 5+10+20+3+2 ) / 5
print(np.mean(array,key=lambda x:x[1]))
TypeError: mean() got an unexpected keyword argument 'key'
array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
sum = 0
for i in range(len(array)):
sum = sum + array[i][1]
average = sum / len(array)
print(average)
import numpy as np
print(np.mean(array,key=lambda x:x[1]))
How can avoid this?
I want to use second example.
python arrays python-3.x tuples average
I want to write this code as pythonic. My real array much bigger than this example.
( 5+10+20+3+2 ) / 5
print(np.mean(array,key=lambda x:x[1]))
TypeError: mean() got an unexpected keyword argument 'key'
array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
sum = 0
for i in range(len(array)):
sum = sum + array[i][1]
average = sum / len(array)
print(average)
import numpy as np
print(np.mean(array,key=lambda x:x[1]))
How can avoid this?
I want to use second example.
python arrays python-3.x tuples average
python arrays python-3.x tuples average
edited 41 mins ago
ruohola
1,884420
1,884420
asked 2 hours ago
Şevval KahramanŞevval Kahraman
695
695
What version of Python are you using?
– Peter Wood
2 hours ago
1
@PeterWood python 3.7
– Şevval Kahraman
1 hour ago
add a comment |
What version of Python are you using?
– Peter Wood
2 hours ago
1
@PeterWood python 3.7
– Şevval Kahraman
1 hour ago
What version of Python are you using?
– Peter Wood
2 hours ago
What version of Python are you using?
– Peter Wood
2 hours ago
1
1
@PeterWood python 3.7
– Şevval Kahraman
1 hour ago
@PeterWood python 3.7
– Şevval Kahraman
1 hour ago
add a comment |
7 Answers
7
active
oldest
votes
If you are using Python 3.4 or above, you could use the statistics
module:
from statistics import mean
average = mean(value[1] for value in array)
Or if you're using a version of Python older than 3.4:
average = sum(value[1] for value in array) / len(array)
If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:
>>> 25 / 4
6
>>> 25 / float(4)
6.25
To ensure we don't have integer division we could set the starting value of sum
to be the float
value 0.0
. However, this also means we have to make the loop over the values in the array into a comprehension expression, otherwise it's a syntax error, and it's less pretty, as noted in the comments:
average = sum((value[1] for value in array), 0.0) / len(array)
It's probably best to use fsum
from the math
module which will return a float
:
from math import fsum
average = fsum(value[1] for value in array) / len(array)
I realised there are better ways to do the Python 2 code.sum
takes an argument for the starting value. If you pass0.0
to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in themath
module,fsum
.
– Peter Wood
1 hour ago
I would say thefloat
casting way is little bit more self-explanatory than passing a weird0.0
value argument for thesum
.
– ruohola
37 mins ago
@ruohola I think usingfsum
is probably best for Python 2.
– Peter Wood
24 mins ago
add a comment |
You could use map
:
np.mean(list(map(lambda x: x[1], array)))
works, thanks a lot
– Şevval Kahraman
1 hour ago
add a comment |
With pure Python:
from operator import itemgetter
acc = 0
count = 0
for value in map(itemgetter(1), array):
acc += value
count += 1
mean = acc / count
An iterative approach can be preferable if your data cannot fit in memory as a list
(since you said it was big). If it can, prefer a declarative approach:
data = [sub[1] for sub in array]
mean = sum(data) / len(data)
If you are open to using numpy
, I find this cleaner:
a = np.array(array)
mean = a[:, 1].astype(int).mean()
add a comment |
Just find the average using sum and number of elements of the list.
array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
avg = float(sum(value[1] for value in array)) / float(len(array))
print(avg)
#8.0
Fixed it, Thank you for the suggestion @PeterWood
– Devesh Kumar Singh
2 hours ago
add a comment |
you can use map
instead of list comprehension
sum(map(lambda x:int(x[1]), array)) / len(array)
or functools.reduce
(if you use Python2.X just reduce
not functools.reduce
)
import functools
functools.reduce(lambda acc, y: acc + y[1], array, 0) / len(array)
first one gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
add a comment |
Besides all the nice and cool answers below, there is something in your example code that is not pythonic at all, the for loop with range/len. This can be written, amongst other even more sophisticated ways, like:
for i in array:
sum = sum + i[1]
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– manish
9 mins ago
add a comment |
You can simply use:
print(sum(tup[1] for tup in array) / len(array))
Or for Python 2:
print(sum(tup[1] for tup in array) / float(len(array)))
Or little bit more concisely for Python 2:
from math import fsum
print(fsum(tup[1] for tup in array) / len(array))
it gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
@DeveshKumarSingh just need to cast the len to a float for python2:float(len(array))
.
– ruohola
54 mins ago
@ŞevvalKahraman it gives no errors for me with your examplearray
, you probably have a typo somewhere.
– ruohola
53 mins ago
@ruohola The reason it works for the example is it's40 / 5
which gives8
with no remainder. In Python 2, with different numbers, it could truncate the answer.
– Peter Wood
49 mins ago
@PeterWood it will not truncate anything if you use thefloat(len(array))
casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.
– ruohola
44 mins ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55843611%2fis-there-any-pythonic-way-to-find-average-of-specific-tuple-elements-in-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
If you are using Python 3.4 or above, you could use the statistics
module:
from statistics import mean
average = mean(value[1] for value in array)
Or if you're using a version of Python older than 3.4:
average = sum(value[1] for value in array) / len(array)
If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:
>>> 25 / 4
6
>>> 25 / float(4)
6.25
To ensure we don't have integer division we could set the starting value of sum
to be the float
value 0.0
. However, this also means we have to make the loop over the values in the array into a comprehension expression, otherwise it's a syntax error, and it's less pretty, as noted in the comments:
average = sum((value[1] for value in array), 0.0) / len(array)
It's probably best to use fsum
from the math
module which will return a float
:
from math import fsum
average = fsum(value[1] for value in array) / len(array)
I realised there are better ways to do the Python 2 code.sum
takes an argument for the starting value. If you pass0.0
to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in themath
module,fsum
.
– Peter Wood
1 hour ago
I would say thefloat
casting way is little bit more self-explanatory than passing a weird0.0
value argument for thesum
.
– ruohola
37 mins ago
@ruohola I think usingfsum
is probably best for Python 2.
– Peter Wood
24 mins ago
add a comment |
If you are using Python 3.4 or above, you could use the statistics
module:
from statistics import mean
average = mean(value[1] for value in array)
Or if you're using a version of Python older than 3.4:
average = sum(value[1] for value in array) / len(array)
If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:
>>> 25 / 4
6
>>> 25 / float(4)
6.25
To ensure we don't have integer division we could set the starting value of sum
to be the float
value 0.0
. However, this also means we have to make the loop over the values in the array into a comprehension expression, otherwise it's a syntax error, and it's less pretty, as noted in the comments:
average = sum((value[1] for value in array), 0.0) / len(array)
It's probably best to use fsum
from the math
module which will return a float
:
from math import fsum
average = fsum(value[1] for value in array) / len(array)
I realised there are better ways to do the Python 2 code.sum
takes an argument for the starting value. If you pass0.0
to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in themath
module,fsum
.
– Peter Wood
1 hour ago
I would say thefloat
casting way is little bit more self-explanatory than passing a weird0.0
value argument for thesum
.
– ruohola
37 mins ago
@ruohola I think usingfsum
is probably best for Python 2.
– Peter Wood
24 mins ago
add a comment |
If you are using Python 3.4 or above, you could use the statistics
module:
from statistics import mean
average = mean(value[1] for value in array)
Or if you're using a version of Python older than 3.4:
average = sum(value[1] for value in array) / len(array)
If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:
>>> 25 / 4
6
>>> 25 / float(4)
6.25
To ensure we don't have integer division we could set the starting value of sum
to be the float
value 0.0
. However, this also means we have to make the loop over the values in the array into a comprehension expression, otherwise it's a syntax error, and it's less pretty, as noted in the comments:
average = sum((value[1] for value in array), 0.0) / len(array)
It's probably best to use fsum
from the math
module which will return a float
:
from math import fsum
average = fsum(value[1] for value in array) / len(array)
If you are using Python 3.4 or above, you could use the statistics
module:
from statistics import mean
average = mean(value[1] for value in array)
Or if you're using a version of Python older than 3.4:
average = sum(value[1] for value in array) / len(array)
If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:
>>> 25 / 4
6
>>> 25 / float(4)
6.25
To ensure we don't have integer division we could set the starting value of sum
to be the float
value 0.0
. However, this also means we have to make the loop over the values in the array into a comprehension expression, otherwise it's a syntax error, and it's less pretty, as noted in the comments:
average = sum((value[1] for value in array), 0.0) / len(array)
It's probably best to use fsum
from the math
module which will return a float
:
from math import fsum
average = fsum(value[1] for value in array) / len(array)
edited 32 mins ago
answered 2 hours ago
Peter WoodPeter Wood
16.8k33876
16.8k33876
I realised there are better ways to do the Python 2 code.sum
takes an argument for the starting value. If you pass0.0
to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in themath
module,fsum
.
– Peter Wood
1 hour ago
I would say thefloat
casting way is little bit more self-explanatory than passing a weird0.0
value argument for thesum
.
– ruohola
37 mins ago
@ruohola I think usingfsum
is probably best for Python 2.
– Peter Wood
24 mins ago
add a comment |
I realised there are better ways to do the Python 2 code.sum
takes an argument for the starting value. If you pass0.0
to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in themath
module,fsum
.
– Peter Wood
1 hour ago
I would say thefloat
casting way is little bit more self-explanatory than passing a weird0.0
value argument for thesum
.
– ruohola
37 mins ago
@ruohola I think usingfsum
is probably best for Python 2.
– Peter Wood
24 mins ago
I realised there are better ways to do the Python 2 code.
sum
takes an argument for the starting value. If you pass 0.0
to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in the math
module, fsum
.– Peter Wood
1 hour ago
I realised there are better ways to do the Python 2 code.
sum
takes an argument for the starting value. If you pass 0.0
to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in the math
module, fsum
.– Peter Wood
1 hour ago
I would say the
float
casting way is little bit more self-explanatory than passing a weird 0.0
value argument for the sum
.– ruohola
37 mins ago
I would say the
float
casting way is little bit more self-explanatory than passing a weird 0.0
value argument for the sum
.– ruohola
37 mins ago
@ruohola I think using
fsum
is probably best for Python 2.– Peter Wood
24 mins ago
@ruohola I think using
fsum
is probably best for Python 2.– Peter Wood
24 mins ago
add a comment |
You could use map
:
np.mean(list(map(lambda x: x[1], array)))
works, thanks a lot
– Şevval Kahraman
1 hour ago
add a comment |
You could use map
:
np.mean(list(map(lambda x: x[1], array)))
works, thanks a lot
– Şevval Kahraman
1 hour ago
add a comment |
You could use map
:
np.mean(list(map(lambda x: x[1], array)))
You could use map
:
np.mean(list(map(lambda x: x[1], array)))
answered 2 hours ago
pdpinopdpino
1667
1667
works, thanks a lot
– Şevval Kahraman
1 hour ago
add a comment |
works, thanks a lot
– Şevval Kahraman
1 hour ago
works, thanks a lot
– Şevval Kahraman
1 hour ago
works, thanks a lot
– Şevval Kahraman
1 hour ago
add a comment |
With pure Python:
from operator import itemgetter
acc = 0
count = 0
for value in map(itemgetter(1), array):
acc += value
count += 1
mean = acc / count
An iterative approach can be preferable if your data cannot fit in memory as a list
(since you said it was big). If it can, prefer a declarative approach:
data = [sub[1] for sub in array]
mean = sum(data) / len(data)
If you are open to using numpy
, I find this cleaner:
a = np.array(array)
mean = a[:, 1].astype(int).mean()
add a comment |
With pure Python:
from operator import itemgetter
acc = 0
count = 0
for value in map(itemgetter(1), array):
acc += value
count += 1
mean = acc / count
An iterative approach can be preferable if your data cannot fit in memory as a list
(since you said it was big). If it can, prefer a declarative approach:
data = [sub[1] for sub in array]
mean = sum(data) / len(data)
If you are open to using numpy
, I find this cleaner:
a = np.array(array)
mean = a[:, 1].astype(int).mean()
add a comment |
With pure Python:
from operator import itemgetter
acc = 0
count = 0
for value in map(itemgetter(1), array):
acc += value
count += 1
mean = acc / count
An iterative approach can be preferable if your data cannot fit in memory as a list
(since you said it was big). If it can, prefer a declarative approach:
data = [sub[1] for sub in array]
mean = sum(data) / len(data)
If you are open to using numpy
, I find this cleaner:
a = np.array(array)
mean = a[:, 1].astype(int).mean()
With pure Python:
from operator import itemgetter
acc = 0
count = 0
for value in map(itemgetter(1), array):
acc += value
count += 1
mean = acc / count
An iterative approach can be preferable if your data cannot fit in memory as a list
(since you said it was big). If it can, prefer a declarative approach:
data = [sub[1] for sub in array]
mean = sum(data) / len(data)
If you are open to using numpy
, I find this cleaner:
a = np.array(array)
mean = a[:, 1].astype(int).mean()
edited 2 hours ago
answered 2 hours ago
gmdsgmds
8,040932
8,040932
add a comment |
add a comment |
Just find the average using sum and number of elements of the list.
array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
avg = float(sum(value[1] for value in array)) / float(len(array))
print(avg)
#8.0
Fixed it, Thank you for the suggestion @PeterWood
– Devesh Kumar Singh
2 hours ago
add a comment |
Just find the average using sum and number of elements of the list.
array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
avg = float(sum(value[1] for value in array)) / float(len(array))
print(avg)
#8.0
Fixed it, Thank you for the suggestion @PeterWood
– Devesh Kumar Singh
2 hours ago
add a comment |
Just find the average using sum and number of elements of the list.
array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
avg = float(sum(value[1] for value in array)) / float(len(array))
print(avg)
#8.0
Just find the average using sum and number of elements of the list.
array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
avg = float(sum(value[1] for value in array)) / float(len(array))
print(avg)
#8.0
edited 2 hours ago
answered 2 hours ago
Devesh Kumar SinghDevesh Kumar Singh
3,4421425
3,4421425
Fixed it, Thank you for the suggestion @PeterWood
– Devesh Kumar Singh
2 hours ago
add a comment |
Fixed it, Thank you for the suggestion @PeterWood
– Devesh Kumar Singh
2 hours ago
Fixed it, Thank you for the suggestion @PeterWood
– Devesh Kumar Singh
2 hours ago
Fixed it, Thank you for the suggestion @PeterWood
– Devesh Kumar Singh
2 hours ago
add a comment |
you can use map
instead of list comprehension
sum(map(lambda x:int(x[1]), array)) / len(array)
or functools.reduce
(if you use Python2.X just reduce
not functools.reduce
)
import functools
functools.reduce(lambda acc, y: acc + y[1], array, 0) / len(array)
first one gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
add a comment |
you can use map
instead of list comprehension
sum(map(lambda x:int(x[1]), array)) / len(array)
or functools.reduce
(if you use Python2.X just reduce
not functools.reduce
)
import functools
functools.reduce(lambda acc, y: acc + y[1], array, 0) / len(array)
first one gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
add a comment |
you can use map
instead of list comprehension
sum(map(lambda x:int(x[1]), array)) / len(array)
or functools.reduce
(if you use Python2.X just reduce
not functools.reduce
)
import functools
functools.reduce(lambda acc, y: acc + y[1], array, 0) / len(array)
you can use map
instead of list comprehension
sum(map(lambda x:int(x[1]), array)) / len(array)
or functools.reduce
(if you use Python2.X just reduce
not functools.reduce
)
import functools
functools.reduce(lambda acc, y: acc + y[1], array, 0) / len(array)
edited 2 hours ago
answered 2 hours ago
minjiminji
157110
157110
first one gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
add a comment |
first one gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
first one gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
first one gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
add a comment |
Besides all the nice and cool answers below, there is something in your example code that is not pythonic at all, the for loop with range/len. This can be written, amongst other even more sophisticated ways, like:
for i in array:
sum = sum + i[1]
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– manish
9 mins ago
add a comment |
Besides all the nice and cool answers below, there is something in your example code that is not pythonic at all, the for loop with range/len. This can be written, amongst other even more sophisticated ways, like:
for i in array:
sum = sum + i[1]
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– manish
9 mins ago
add a comment |
Besides all the nice and cool answers below, there is something in your example code that is not pythonic at all, the for loop with range/len. This can be written, amongst other even more sophisticated ways, like:
for i in array:
sum = sum + i[1]
Besides all the nice and cool answers below, there is something in your example code that is not pythonic at all, the for loop with range/len. This can be written, amongst other even more sophisticated ways, like:
for i in array:
sum = sum + i[1]
answered 30 mins ago
carnicercarnicer
1476
1476
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– manish
9 mins ago
add a comment |
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– manish
9 mins ago
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– manish
9 mins ago
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
– manish
9 mins ago
add a comment |
You can simply use:
print(sum(tup[1] for tup in array) / len(array))
Or for Python 2:
print(sum(tup[1] for tup in array) / float(len(array)))
Or little bit more concisely for Python 2:
from math import fsum
print(fsum(tup[1] for tup in array) / len(array))
it gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
@DeveshKumarSingh just need to cast the len to a float for python2:float(len(array))
.
– ruohola
54 mins ago
@ŞevvalKahraman it gives no errors for me with your examplearray
, you probably have a typo somewhere.
– ruohola
53 mins ago
@ruohola The reason it works for the example is it's40 / 5
which gives8
with no remainder. In Python 2, with different numbers, it could truncate the answer.
– Peter Wood
49 mins ago
@PeterWood it will not truncate anything if you use thefloat(len(array))
casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.
– ruohola
44 mins ago
add a comment |
You can simply use:
print(sum(tup[1] for tup in array) / len(array))
Or for Python 2:
print(sum(tup[1] for tup in array) / float(len(array)))
Or little bit more concisely for Python 2:
from math import fsum
print(fsum(tup[1] for tup in array) / len(array))
it gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
@DeveshKumarSingh just need to cast the len to a float for python2:float(len(array))
.
– ruohola
54 mins ago
@ŞevvalKahraman it gives no errors for me with your examplearray
, you probably have a typo somewhere.
– ruohola
53 mins ago
@ruohola The reason it works for the example is it's40 / 5
which gives8
with no remainder. In Python 2, with different numbers, it could truncate the answer.
– Peter Wood
49 mins ago
@PeterWood it will not truncate anything if you use thefloat(len(array))
casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.
– ruohola
44 mins ago
add a comment |
You can simply use:
print(sum(tup[1] for tup in array) / len(array))
Or for Python 2:
print(sum(tup[1] for tup in array) / float(len(array)))
Or little bit more concisely for Python 2:
from math import fsum
print(fsum(tup[1] for tup in array) / len(array))
You can simply use:
print(sum(tup[1] for tup in array) / len(array))
Or for Python 2:
print(sum(tup[1] for tup in array) / float(len(array)))
Or little bit more concisely for Python 2:
from math import fsum
print(fsum(tup[1] for tup in array) / len(array))
edited 22 mins ago
answered 2 hours ago
ruoholaruohola
1,884420
1,884420
it gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
@DeveshKumarSingh just need to cast the len to a float for python2:float(len(array))
.
– ruohola
54 mins ago
@ŞevvalKahraman it gives no errors for me with your examplearray
, you probably have a typo somewhere.
– ruohola
53 mins ago
@ruohola The reason it works for the example is it's40 / 5
which gives8
with no remainder. In Python 2, with different numbers, it could truncate the answer.
– Peter Wood
49 mins ago
@PeterWood it will not truncate anything if you use thefloat(len(array))
casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.
– ruohola
44 mins ago
add a comment |
it gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
@DeveshKumarSingh just need to cast the len to a float for python2:float(len(array))
.
– ruohola
54 mins ago
@ŞevvalKahraman it gives no errors for me with your examplearray
, you probably have a typo somewhere.
– ruohola
53 mins ago
@ruohola The reason it works for the example is it's40 / 5
which gives8
with no remainder. In Python 2, with different numbers, it could truncate the answer.
– Peter Wood
49 mins ago
@PeterWood it will not truncate anything if you use thefloat(len(array))
casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.
– ruohola
44 mins ago
it gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
it gives this error : 'int' object is not callable
– Şevval Kahraman
1 hour ago
@DeveshKumarSingh just need to cast the len to a float for python2:
float(len(array))
.– ruohola
54 mins ago
@DeveshKumarSingh just need to cast the len to a float for python2:
float(len(array))
.– ruohola
54 mins ago
@ŞevvalKahraman it gives no errors for me with your example
array
, you probably have a typo somewhere.– ruohola
53 mins ago
@ŞevvalKahraman it gives no errors for me with your example
array
, you probably have a typo somewhere.– ruohola
53 mins ago
@ruohola The reason it works for the example is it's
40 / 5
which gives 8
with no remainder. In Python 2, with different numbers, it could truncate the answer.– Peter Wood
49 mins ago
@ruohola The reason it works for the example is it's
40 / 5
which gives 8
with no remainder. In Python 2, with different numbers, it could truncate the answer.– Peter Wood
49 mins ago
@PeterWood it will not truncate anything if you use the
float(len(array))
casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.– ruohola
44 mins ago
@PeterWood it will not truncate anything if you use the
float(len(array))
casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.– ruohola
44 mins ago
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55843611%2fis-there-any-pythonic-way-to-find-average-of-specific-tuple-elements-in-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What version of Python are you using?
– Peter Wood
2 hours ago
1
@PeterWood python 3.7
– Şevval Kahraman
1 hour ago