简体   繁体   中英

How to add specific elements (that are strings) in a List of Lists?

This is my List of Lists. Notice that the elements are strings:

BTC_USDT = [['16941.19', '0.000796'], ['16941.98', '0.205845'], ['16941.99', '0.011509'], ['16942.34', '0.043801'],
            ['16942.35', '0.253870'], ['16942.36', '0.572059'], ['16942.41', '0.129081'], ['16942.42', '0.017000'],
            ['16942.43', '0.003698'], ['16942.44', '0.048544'], ['16942.52', '0.005100'], ['16942.53', '0.017272'],
            ['16942.56', '0.010200'], ['16942.57', '0.010268'], ['16942.58', '0.010192'], ['16942.59', '0.001071'],
            ['16942.60', '0.011390'], ['16942.64', '0.010115'], ['16942.67', '0.032785'], ['16942.68', '0.062645']]

I'm trying to output a sum all the 2-nd elements. And I've come this far:

for i in range(len(BTC_USDT)):
    ob_quantities = BTC_USDT[i][1]
    print(ob_quantities)

This will print the sum of all the 2nd elements:

total_sum = 0
for element in BTC_USDT:
    total_sum += float(element[1])
print(total_sum)

or, to put it another way:

total_sum = sum([float(element[1]) for element in BTC_USDT])
print(total_sum)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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