Input
['select', '*', 'from', 'ak','.','person']
I need to create a dictionary and merger the element after from
Expected Output
['select', '*', 'from', 'ak.person']
Code is below
m = []
for i in a:
if '.' == i:
ind = a.index('.')
m.append(a[ind-1] a[ind] a[ind 1])
else:
m.append(i)
My output >> ['select', '*', 'from', 'ak', 'ak.person', 'person']
Expected is ['select', '*', 'from', 'ak.person']
CodePudding user response:
The loop here checks if the previous element is 'from' and if so, it joins the following three elements that comes after it.
This should work for the test cases that follow the same pattern like you've given (also including longer queries with where
mentioned in the updated question) .
a = ['select', '*', 'from', 'ak','.','person']
m = []
while i< len(a):
if a[i-1] == "from":
m.append("".join(a[i:i 3]))
i =3
else:
m.append(a[i])
i =1
Output
['select', '*', 'from', 'ak.person']
CodePudding user response:
Relatively short:
arr = ['select', '*', 'from', 'ak','.','person']
ind = arr.index('from') 1
# we join the initial array until 'from' then joining the rest:
print(arr[:ind] ["".join(arr[ind:])])
CodePudding user response:
Try this. I first extracted a sub-list after 'from' and merged that.
orig = ['select', '*', 'from', 'ak', '.' ,'person']
from_pos = orig.index('from')
sublist = orig[from_pos 1:from_pos 4]
new_string = ''
for txt in sublist:
new_string = txt
new_list = orig[0:from_pos 1]
new_list.append(new_string)
print(orig)
print(new_list)
And if you have any where clause or group by after that, you can try this -
orig = ['select', '*', 'from', 'ak', '.' ,'person', 'where', 'filter', 'group', 'by']
from_pos = orig.index('from')
sublist = orig[from_pos 1:from_pos 4]
new_string = ''
for txt in sublist:
new_string = txt
new_list = orig[0:from_pos 1]
new_list.append(new_string)
where = orig[from_pos 4:]
new_list = new_list where
print(orig)
print(new_list)
You get -
['select', '*', 'from', 'ak.person', 'where', 'filter', 'group', 'by']
CodePudding user response:
Try this:
def my_func(my_list):
lp=my_list[(my_list.index('from') 1):(len(my_list))]
t="".join(lp)
ans=my_list[0:(my_list.index('from') 1)] [t]
return ans
my_func(['select', '*', 'from', 'ak','.','person'])
Output:
['select', '*', 'from', 'ak.person']
CodePudding user response:
Golf answer: print(a[:(i:=(a:=['select', '*', 'from', 'ak','.','person']).index('from') 1)] [''.join(a[i:])])