Home > front end >  List comprehension with loop and conditions
List comprehension with loop and conditions

Time:02-25

I'd like to transform this Python code (below) into a list comprehension :

def list1(a):
  L = [100]
  n = int((L[0] - a)/0.2)
  for i in range (n):
    var = L[i]-0.2
    var = round(var,2) if var * 100 % 100 != 0 else int(var)
    L.append(var)
  return L

print(list1(25))

I've tried that but it didn't work :

def list2(a):
  L = [100]
  n = int((L[0] - a)/0.2)
  i = 0
  var = L[i]-0.2
  L = [L[i]-0.2 for i in range (n) round(var,2) if (var) * 100 % 100 != 0 else int(var)]
  return L

print(list2(25))

Can you help me please ?

CodePudding user response:

You can access a list while building the list using a generator expression with list.extend. This approach has no advantages over a for loop and is less readable. Using a single list comprehension is not possible in your use case.

def list2(a):
  L = [100]
  n = int((L[0] - a)/0.2)
  L.extend(round(L[i]-0.2,2) if (L[i]-0.2) * 100 % 100 != 0 else int(L[i]-0.2) for i in range(n))
  return L
list2(25) == list1(25)

Output

True
  • Related