Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting all elements in list from a specific number

Tags:

python

Can I do an operation where I minus my list from a number using python? for example:

a = [2, 4, 6, 8, 10]

I would then do 1 - a

The output should be:

a = [-1, -3, -5, -7, -9] 

a in my code is a list of floats pulled from a .csv file, is this kind of operation possible in python?

I am creating my list this way:

f2 = 'C:/Users/.....csv'
with open(f2,'r') as csvfile:
    csvreader = csv.reader(csvfile)
    for line in csvreader:
        l2.append(list(line))

l2 contains lists of floats.

like image 598
MiguelA Avatar asked Sep 01 '25 06:09

MiguelA


2 Answers

You can use a list comprehension

>>> values = [2, 4, 6, 8, 10]
>>> [1 - value for value in values]
[-1, -3, -5, -7, -9]

edit: If you really have a list of lists:

>>> values = [[2, 4, 6], [8, 10, 12]]
>>> [[1 - value for value in sublist]
...   for sublist in values]
[[-1, -3, -5], [-7, -9, -11]]
like image 122
Peter Wood Avatar answered Sep 02 '25 18:09

Peter Wood


A simple for loop will do it:

atemp = [2,4,6,8,10]
a=[]
for i in atemp:
    a.append((1 - i))

Out:

[-1, -3, -5, -7, -9]

Or a list comprehension:

a = [1 - x for x in atemp]

Out:

a

[-1, -3, -5, -7, -9]
like image 27
nipy Avatar answered Sep 02 '25 19:09

nipy