I have to compare 2 lists of strings fetched from the database and from a CSV file respectively.
The data objects could vary in length.
The condition
if obj1 >= obj2 the perform the code. but since the data can vary in length I have to hard code every possibility according to the length of the objects, which is tiring and wrong.
According to the code if a obj1 length is greater than obj2 length then perform the program.
Can you please tell me a way where I can compare a string of length 8 and length 4 (example numbers) without hard coding it through if else. I believe this is achievable through while loop. Which is sadly my weak point. and this comparison goes until the first character is reached and when WHILE reaches 0 it breaks.
Meaning if I get an object of length 2 and the other object length is 3, How can I perform recursive compressing of the objects through while loop.
HELP would be greatly appreciated.
I hope you get the question.
def LCR():
dest = Destination.objects.values_list('dest_num', flat=True)
# This method turn the fetched data into a list. Example
#['1233','4412','23135','123']
rates = {}
ratelist = {}
csv_file = open(r'.\adoc.csv')
data_set = csv_file.read().decode("UTF-8")
io_string = io.StringIO(data_set)
next(io_string)
for column in csv.reader(io_string, delimiter=str(u",")):
rates[column[0]] = column[1]
#Example data
#['8523654','754','4563']
for desNum in dest:
desNum = str(desNum)
# print type(desNum)
for venNum, venValue in rates.items():
venlen = len(venNum)
deslen = len(desNum)
if venlen >= deslen:
if desNum[:-1] == venNum[:-1] and desNum[:-2] == venNum[:-2] and desNum[:-3] == venNum[:-3]:
print (venNum)
print (desNum)
# print "Works well"
# print ('====================')
ratelist[venNum] = venValue
elif desNum[:-1] == venNum[:-2] and desNum[:-2] == venNum[:-3] and desNum[:-3] == venNum[:-4]:
# ratelist[venNum] = venValue
print (venNum)
print (desNum)
elif desNum[:-1] == desNum[:-3] and desNum[:-2] == venNum[:-4] and desNum[:-3] == venNum[:-5]:
# ratelist[venNum] = venValue
print (venNum)
print (desNum)
elif desNum[:-1] == venNum[:-4] and desNum[:-2] == venNum[:-5]:
# ratelist[venNum] = venValue
print (venNum)
print (desNum)
elif desNum[:-1] == venNum[:-5] and desNum[:-2] == venNum[:-6]:
# ratelist[venNum] = venValue
print (venNum)
print (desNum)
else:
print "LENGTH ERROR"
print ratelist
venNumstarts withdesNum?if venNum.startswith(desNum)rather than all of those nested if statementsvenNum.startswith(desNum)is exactly doing that.