Home > front end >  Sum up all Floats in a List of 'Mixed' Elements
Sum up all Floats in a List of 'Mixed' Elements

Time:05-14

What are some primitive ways to get a sum of all floats in a list that looks like this:

list_1 = [['coffee', 6.99], ['cream', 0.6], ['berries', 3.5], ['milk', 1.45], ['chocolate', 0.85]]

I tried removing string values from list_1 and appending floats to a temporary list to get a list of pure floats, but it seems I'm missing something.

Edit:

Thank you! @luk2302 solution worked for me.

I am sorry that this post looked like a lazy attempt to get a fast solution. I actually tried solving it and googling for solution for about 3 hours, but some solutions didn't work and some seemed too complicated (i.e. including topics I've not studied yet).

I was a bit ashamed to put the solutions I've tried because I realise this must be a very basic problem. But here's what I've tried as far as I can remember:

1)

for a in list_1:
    sum(a[1])
list_2 = []
for a in list_1:
    if list_1[a].isdigit():
        list_2.append(a)
for a in list_1:
    if isinstance(a[0], str):
        list_1.remove(a[0])
list_2 = []
for a in list_1:
    if isinstance(a[1], float):
        list_2.append(a[1])

I wonder if any of these methods could work with some small tweaks.

CodePudding user response:

That depend if you always have a list of lists. Something like this could works

list_1 = [['coffee', 6.99], ['cream', 0.6], ['berries', 3.5], ['milk', 1.45], ['chocolate', 0.85]]

flat_list = [item for sublist in list_1 for item in sublist]

sum = 0.
for l in flat_list:
    if type(l) == type(0.):
        sum  = l
print(sum)  

or something like

list_1 = [['coffee', 6.99], ['cream', 0.6], ['berries', 3.5], ['milk', 1.45], ['chocolate', 0.85]]
flat_list = [item for sublist in list_1 for item in sublist]
only_float_list = [item  for item in flat_list if type(item) == type(0.) ]
print(sum(only_float_list))

CodePudding user response:

Use zip to decouple the list of pairs into a tuple of strings and a tuple of numbers. sum the numbers.

list_1 = [['coffee', 6.99], ['cream', 0.6], ['berries', 3.5], ['milk', 1.45], ['chocolate', 0.85]]

_, nums = zip(*list_1)
print(sum(nums))

CodePudding user response:

since the lists that holds the item name and the float are found within another parent list, you can use code below to sum up all the floats in the sub array elements.

list_1 = [['coffee', 6.99], ['cream', 0.6], ['berries', 3.5], ['milk', 1.45], ['chocolate', 0.85]]
# initialize the sum to 0
sum=0
for lst in list_1:
    val=lst[1] #use the second el index to access the floats
    sum =val
print(sum)
    
  • Related