How to multiply every third element of a list together if the first elements are the same?

Hertzeh :

Say I have a nested list of multiple stocks, where the first element of the sub-lists is the stock number and the other two are the date and value. For example:

A = [[120, 'Date1', 1.03], [120, 'Date2', 1.04], [120, 'Date3', 1.02], [240, 'Date1', 1.06], [240, 'Date2', 0.98], [240, 'Date3', 1.04], [381, 'Date2', 1.03], [381, 'Date3', 0.85]]. 

(Note, the number of values per stock does not have to be the same, for example in the stock number 381 only has two dates and values where as 240 and 1120 have three dates and values.)

How would I create a list which contains the product of the third elements of all lists characterized by the first element? I have started by trying:

A1 = 1
for i in range(len(A)-1):
    if A[i][0] == A[i + 1][0]:
        A1 = A1 * A[i][2]

print(A1)

This code only works well for one stock number. When there are more it of course doesn't hold. So for all sub-lists that start with 120, I want to multiply all of the elements together and append that number to a list, then do the same for the next numbers (I want to do this for a nested list of any size).

In this case I would get

[1.092624, 1.08035, 0.8755]

How would I do this for the list A given. How would I do this for any length nested list.

Shadesfear :

So a simple approach to this, is using a dictionary to store each unique value as such

A = [[120, 'Date1', 1.03], [120, 'Date2', 1.04], [120, 'Date3', 1.02], [240, 'Date1', 1.06], [240, 'Date2', 0.98], [240, 'Date3', 1.04], [381, 'Date2', 1.03], [381, 'Date3', 0.85]]

B = {}

for li in A:
    if not li[0] in B:
        B[li[0]] = 1
    B[li[0]] *= li[2]

 print(B)

this gives

>>> {120: 1.0926240000000003, 240: 1.080352, 381: 0.8755}

if you want it as a list only, use:

print(list(B.values()))



>>> [1.0926240000000003, 1.080352, 0.8755]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13888&siteId=1