简体   繁体   English

如果第一个元素相同,如何将列表的每三个元素相乘?

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

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.) (注意,每只股票的价值数量不必相同,例如在股票编号 381 中只有两个日期和值,而 240 和 1120 具有三个日期和值。)

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).因此,对于以 120 开头的所有子列表,我想将所有元素相乘并将该数字附加到列表中,然后对下一个数字执行相同操作(我想对任何大小的嵌套列表执行此操作) .

In this case I would get在这种情况下,我会得到

[1.092624, 1.08035, 0.8755]

How would I do this for the list A given.我将如何为给定的列表 A 执行此操作。 How would I do this for any length nested list.对于任何长度的嵌套列表,我将如何执行此操作。

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]

More Pythonic Way would be:更多的 Pythonic 方式是:

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]]

X = [ {i[0]:i[2]}  for i in A]

result = dict(functools.reduce(operator.add, map(collections.Counter, X))).values()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM