首页 > 解决方案 > How to addition two value in list of list

问题描述

can someone explain to me how i can addition two value in list of list ?

Here my list of list :

data =  [
   ["Autofollow", 7200, "00:00:00:00", "Name Of File0", "28/07/2021"],  # Line 1
   ["Autofollow", 300 , "00:00:00:00", "Name Of File2", "28/07/2021"],  # Line 2
   ["Autofollow", 3600, "00:00:00:00", "Name Of file3", "28/07/2021"],  # Line 3
       ]

here i generate randomly data :

i = 0
while i <= 2 :
    dataRand += random.choices(data)
    i += 1

I call the function totalInSecond with list dataRand :

 print(totalInSecod(dataRand))

here the function which must add the values ​​of value1 :

def totalInSecod(someRandomData) :
    global sumDurationInSecond
    print(someRandomData)
    for value in someRandomData :
        sumDurationInSecond += value[1]
        return sumDurationInSecond

but the result does not add all the values ​​of my list of list..

I have this result :

[['Autofollow', 3600, '00:00:00:00', 'Name Of file3', '28/07/2021'], ['Autofollow', 7200, '00:00:00:00', 'Name Of File0', '28/07/2021']]
3600

I would like to have 3600 + 7200 = 10800

I'm sorry if this question has already been asked, but I can't find an answer

标签: python

解决方案


你的代码绝对没问题。您只需要返回 after for 循环。

您的代码:

def totalInSecod(someRandomData) :
    sumDurationInSecond = 0
    for value in someRandomData :
        sumDurationInSecond += value[1]
    return sumDurationInSecond

data =  [
   ["Autofollow", 7200, "00:00:00:00", "Name Of File0", "28/07/2021"],  # Line 1
   ["Autofollow", 300 , "00:00:00:00", "Name Of File2", "28/07/2021"],  # Line 2
   ["Autofollow", 3600, "00:00:00:00", "Name Of file3", "28/07/2021"],  # Line 3
       ]
print(totalInSecod(data))

或 一个班轮

def totalInSecod(someRandomData):
    return sum(list(zip(*someRandomData))[1])

data =  [
   ["Autofollow", 7200, "00:00:00:00", "Name Of File0", "28/07/2021"],  # Line 1
   ["Autofollow", 300 , "00:00:00:00", "Name Of File2", "28/07/2021"],  # Line 2
   ["Autofollow", 3600, "00:00:00:00", "Name Of file3", "28/07/2021"],  # Line 3
       ]
print(totalInSecod(data))

输出:11100


推荐阅读