Python: make dual vector dot-product more pythonic

I have this dot product, calculating weighted means, and is applied to two columns in a list:

# calculate weighted values in sequence
for i in range(len(temperatures)-len(weights)):
  temperatures.append(sum([weights[j]*temperatures[i+j][5] for j in range(len(weights))]))
  temperatures.append(sum([weights[j]*temperatures[i+j][6] for j in range(len(weights))]))

The calculation is a running dot-product, ie the list of temperature samples is far larger than the list of weights, hence the correction of subtracting len(weights) at the end of the main loop.
This traverses the list of weights twice, which is inefficient and degrades performance. How could this be done in a more pythonic way?

I also have concerns about the main loop. Would this be considered more pythonic?:

# calculate weighted values in sequence
for i in range(len(temperatures)):
   try:
      # weighted calculation here
   except:
      # do nothing, because array out of bounds

pythonic is more about style and opinion than anything useful for producing a result.

Some sites like stack* in fact, close these kinds of threads and place them in the category of "primarily opinion-based" and close them, as follows:

I tend to agree with this (from a technical perspective this site has never been about these types of "what is more perfect, or stylish or not" discussions - because this is mostly "opinion-based" which has little to do with day-to-day operational code). But if others want to discuss this, go for it.

See this reference:

Pythonic Code: Best Practices to Make Your Python More Readable

If anyone is interested in discussing, go for it.

2 Likes