我目前在python中遇到问题,我想做的是通过6个数组检查是否有负数,然后将一个加到相应的变量中。
我已经尝试了各种方法来解决此问题,但是没有真正的文档可以在网上找到对我有帮助的
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中格式化变量的方法,以便可以逐步将其更改为BusALate,BusBLate等...并在发现负数时添加。
答案 0 :(得分:1)
根据Thierry Lathuille的建议,以下是使用词典如何简化代码的方法:
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)
答案 1 :(得分:0)
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))
答案 2 :(得分:0)
一步即可完成字符串转换和dict理解:
!TCMALLOC_LARGE_ALLOC_REPORT_THRESHOLD=21329330176
!python3 "/content/gdrive/My Drive/my_folder/my_file.py"
这产生
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)