Python Forum

Full Version: Sum only some values from a two-dimensional list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I'm a newbie. I have a two-dimensional list like this
DATA = 0
# quality control flag
QC = 1
samples = [[0.1, 33.3, 4.4], [1, 0, 2]]
where 3 samples and their 3 quality flags are collected. To calculate the average of all the data, I usually do:
mean = sum (map (float, samples[DATA])) / float (len (samples[DATA]))
But now I want to calculate the average using only the data that have flag > 0

I appreciate any help.
zero_data = [data for data, flag in zip(*samples) if flag > 0]
average = sum(zero_data) / len(zero_data)
print(average)
Thank you very much, just what I needed!
I did not know "zip" in Python.