Python Forum
Subtracting Elements of a Sublist in Python 3
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Subtracting Elements of a Sublist in Python 3
#1
Hello,

I am having an issue with subtracting sublists. With the given sublist:

first_list: [[0, 1], [2,4], [8,7]]

There is supposed to be a new list where that contains the difference of the first element from the second element in the sublist:

[-1,-2,-1]

This is the code so far:

for sub_list in data:
differences.append((int(sub_list[1]))-(int(sub_list[0])) in data)

I tried to run this with the other part of the problem to multiply the resulting list, but it fails. It seems to be not iterating. Can anyone offer some suggestions?
Reply
#2
from functools import reduce
import operator


# naive way
def sub_list(iterable):
    result = []
    for sub_list in iterable:
        result.append(sub_list[0] - sub_list[1])
    return result

# as list comprehension
def sub_list2(iterable):
    return [sub_list[0] - sub_list[1] for sub_list in iterable]


# with reduce and operator
def sub_list3(iterable):
    return [reduce(operator.sub, sub_list) for sub_list in iterable]


first_list = [[0, 1], [2,4], [8,7]]
The last function allows to have more than two elements in the sublist.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Thank you for getting back to me.
Reply
#4
note that your expected output is incorrect and not consistent with your attempt at code
elements with index 0 and 1 are calculated as 0-1 and 2-4, while element with index 2 is calculated as 7-8
in your attempt you do int(sub_list[1])-int(sub_list[0]), so basically if that's correct the output is [1, 2, -1]
>>> spam = [[0, 1], [2,4], [8,7]]
>>> [n2-n1 for n1, n2 in spam]
[1, 2, -1]
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Repeating elements when appending in iteration in Python 3.6 miguelsantana 2 3,439 Dec-17-2017, 01:22 AM
Last Post: Terafy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020