Max Best
Max Best

Reputation: 1

How do I format variables in Python

I'm currently having a problem in python, what I am trying to do is go through 6 arrays checking if there is a negative number or not and then adding one to the corresponding variable.

I've tried various things to fix this however there is no real documentation that I can find online that will help me

BusA = ["-1","1","-1","1"]
BusB = ["-1","1","-1","1"]
BusC = ["-1","1","-1","1"]
BusD = ["-1","1","-1","1"]
BusE = ["-1","1","-1","1"]
BusF = ["-1","1","-1","1"]

Buses = "ABCDEF"

BusALate, BusBLate, BusCLate, BusDLate, BusELate, BusFLate = 0, 0, 0, 0, 0, 0

for c in Buses:
  Array = eval("Bus" + str(c))
  for i in Array:
    if(int(i) < 0):
      eval("Bus"+c+"Late") += 1

print(BusALate, BusBLate, BusCLate, BusDLate, BusELate, BusFLate)

If possible I just need a way to format the variable in the if so that it can progressively go through changing it to BusALate, BusBLate etc... and adding when it has found the negative number.

Upvotes: 0

Views: 60

Answers (3)

Jan
Jan

Reputation: 43199

String conversion and dict comprehension in one step:

busses = {'A':["-1","1","-1","1"],
          'B': ["-1","1","-1","1"],
          'C': ["-1","1","-1","1"],
          'D': ["-1","1","-1","1"],
          'E': ["-1","1","-1","1"],
          'F': ["-1","1","-1","1"]}

busses = {key: [(value + 1) if value < 0 else value
                for x in lst
                for value in [int(x)]]
          for key, lst in busses.items()}
print(busses)

This yields

{'A': [0, 1, 0, 1], 
 'B': [0, 1, 0, 1], 
 'C': [0, 1, 0, 1], 
 'D': [0, 1, 0, 1], 
 'E': [0, 1, 0, 1], 
 'F': [0, 1, 0, 1]}

Upvotes: 0

Aaron
Aaron

Reputation: 24812

Building upon Thierry Lathuille's suggestion, here is how using dictionnaries can simplify your code :

bus_schedules= {
    "A" : ["-1","1","-1","1"],
    "B" : ["-1","1","-1","1"],
    "C" : ["-1","1","-1","1"],
    "D" : ["-1","1","-1","1"],
    "E" : ["-1","1","-1","1"],
    "F" : ["-1","1","-1","1"]
}

bus_late = {"A" : 0, "B" : 0, "C" : 0, "D" : 0, "E" : 0, "F" : 0}

for (bus_name, bus_times) in bus_schedules.items():
    for i in bus_times :
        if (int(i) < 0):
            bus_late[bus_name]+=1

print(bus_late)

Upvotes: 1

R&#233;mi Baudoux
R&#233;mi Baudoux

Reputation: 559

import numpy as np

buses =  np.array([[-1,1,-1,1],
                   [-1,1,-1,1],
                   [-1,1,-1,1],
                   [-1,1,-1,1],
                   [-1,1,-1,1],
                   [-1,1,-1,1]])

print(np.sum(buses<0, axis=1))

Upvotes: 0

Related Questions