我刚开始学习编程并决定做一些自我锻炼。
我很难识别,从用逗号和空格分隔的字符串中拆分数据,然后将每个数据分别放到不同的变量中。如果给出的规格总是完整的,我没有问题。我只是使用split然后将索引分配给变量。问题不是所有字符串都有完整的数据。我很难过
specs1 = "100,013km, Automatic, Petrol, 2360cc"
specs2 = "Manual, Diesel, 2500cc"
specs3 = "7,480km, Automatic, Electric"
我想要实现的是输出如下: 规格是用户输入
-------------
Enter specs: 100,013km, Automatic, Petrol, 2360cc
Odometer: 100,013km
Transmission: Automatic
Fuel Type: Petrol
Engine Size: 2360cc
-------------
Enter specs: Manual, Diesel, 2500cc
Odometer: undefined
Transmission: Manual
Fuel Type: Diesel
Engine Size: 2500cc
-------------
Enter specs: 7,480km, Automatic, Electric
Odometer: 7,480km
Transmission: Automatic
Fuel Type: Electric
Engine Size: undefined
有人可以帮助我解决这个问题并解释它。我真的很感激。提前谢谢!
答案 0 :(得分:1)
我建议您使用str.rsplit()来破解逗号字符。
就像这样:s1 = specs1.rsplit(', ')
根据你的目标,不只是使用简单的印刷品或foreach。
答案 1 :(得分:1)
from collections import OrderedDict
specs_dict = OrderedDict([('Odometer', 'undefined'), ('Transmission', 'undefined'), ('Engine Size', 'undefined'), ('Engine Size', 'undefined')])
for spec in specs.split(\'):
if 'km' in spec.lower() or 'mi' in spec.lower():
specs_dict['Odometer'] = spec.strip()
elif 'cc' in spec.lower():
specs_dict['Engine size'] = spec.strip()
elif spec.lower() in ['automatic', 'manual']:
specs_dict['Transmission'] = spec.strip()
else:
specs_dict['Fuel Type'] = spec.strip()
for k, v in specs_dict:
print('{}: {}'.format(k, v))
订购字典会保留您的订单。
最初所有规格都预设为未定义,然后根据用户输入开始设置。
答案 2 :(得分:0)
使用split(str=", ")
拆分输入,然后从临时列表中逐个拉取字符串,并将它们与某些条件进行比较,将它们放在最终列表中的正确位置。
def func(specs_list_temp):
if "km" in specs_list_temp[0]:
specs_list.append(specs_list_temp[0])
specs_list_temp.pop(0)
else:
specs_list.append("undefined")
if specs_list_temp[0] in ("Automatic", "Manual"):
specs_list.append(specs_list_temp[0])
specs_list_temp.pop(0)
else:
specs_list.append("undefined")
if specs_list_temp[0] in ("Petrol", "Diesel", "Electric"):
specs_list.append(specs_list_temp[0])
specs_list_temp.pop(0)
else:
specs_list.append("undefined")
if "cc" in specs_list_temp[0]:
specs_list.append(specs_list_temp[0])
else:
specs_list.append("undefined")
specs1 = "100,013km, Automatic, Petrol, 2360cc"
specs1_list_temp = specs1.split(str=", ")
specs1_list_temp.append("undefined")
specs1_list = func(specs1_list_temp)
答案 3 :(得分:0)
def to_int(s):
"""
Convert a digit string with commas, ie "1,234,567"
to an integer, ie 1234567
"""
return int(s.replace(',', ''))
class Spec:
TRANS_TYPES = {"automatic", "manual"}
FUEL_TYPES = {"diesel", "electric", "petrol"}
@classmethod
def loads(cls, s, sep=", "):
args = {}
for arg in s.split(sep):
arg = arg.strip().lower()
if arg.endswith('km'):
args['odo'] = to_int(arg[:-2].strip())
elif arg in cls.TRANS_TYPES:
args['trans'] = arg
elif arg in cls.FUEL_TYPES:
args['fuel'] = arg
elif arg.endswith('cc'):
args['eng'] = to_int(arg[:-2].strip())
else:
raise ValueError('unrecognized input ({})'.format(arg))
return cls(**args)
def __init__(self, odo=None, trans=None, fuel=None, eng=None):
self.odo = odo
self.trans = trans
self.fuel = fuel
self.eng = eng
def __str__(self):
odo = "undefined" if self.odo is None else "{:,d} km".format(self.odo)
trans = "undefined" if self.trans is None else self.trans.title()
fuel = "undefined" if self.fuel is None else self.fuel.title()
eng = "undefined" if self.eng is None else "{:d}cc".format(self.eng)
return (
"Odometer: {odo}\n"
"Transmission: {trans}\n"
"Fuel Type: {fuel}\n"
"Engine Size: {eng}"
).format(odo=odo, trans=trans, fuel=fuel, eng=eng)
然后
def main():
# data strings
specs = [
"100,013km, Automatic, Petrol, 2360cc",
"Manual, Diesel, 2500cc",
"7,480km, Automatic, Electric"
]
for spec in specs:
print("-------------")
print("Enter specs:", spec)
car = Spec.loads(spec)
print("\n{}\n\n".format(car))
if __name__ == "__main__":
main()
产生
-------------
Enter specs: 100,013km, Automatic, Petrol, 2360cc
Odometer: 100,013 km
Transmission: Automatic
Fuel Type: Petrol
Engine Size: 2360cc
-------------
Enter specs: Manual, Diesel, 2500cc
Odometer: undefined
Transmission: Manual
Fuel Type: Diesel
Engine Size: 2500cc
-------------
Enter specs: 7,480km, Automatic, Electric
Odometer: 7,480 km
Transmission: Automatic
Fuel Type: Electric
Engine Size: undefined