python - 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
解决方案
你的代码绝对没问题。您只需要返回 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
推荐阅读
- python - 如何解决我的python代码中的导入错误?
- ruby - Docker - ruby, nokogiri - 安装 nokogiri (1.10.2) 时出错,
- css - 垂直居中:grid 和 flex 方法有什么区别?
- pyspark - 如何使用 PySpark 测量逻辑回归的精度和召回率?
- eclipse - 附加到 Eclipse 中的 PATH 环境变量
- c# - 确定 Windows 窗体是否在监视器上?
- python - 如何从我当前在机器上的浏览器中打开的网页中获取文本/html?
- javascript - Angular-UI-Select ng-model 不适用于 $scope 上的简单变量
- php - 如何在php中使用exec运行多个命令
- google-cloud-platform - Google Cloud Functions 实现互斥锁的模式是什么