My question is fairly straight forward.
I am trying to concatenate a string with a returned value in a loop. I don't want to add the text to the first occurrence, but to the rest.
Here is the sample code:
list_of_tables = {'k1': 'v1:v2',
'k2':'v3:v4',
'k3':'v5:v6',
'k4':'v7:v8',
'k5':None }
def gen_stmt(val1_name, val2_name):
return 'some text ' val1_name ': ' val2_name
stmt = ''
for k,v in list_of_tables.items():
if v:
pair_val = v.split(':')
fin_value = 'text I need to concat' gen_stmt(*pair_val)
return fin_value
What I need 'text I need to concat' for all the values of k2,k3,k4 and I need to run gen_stmt function for all the keys k1 ...k5
How can I concatenate all the values except the first value?
What I want the output to be
some text v1 : v2 text I need to concat some text v3 : v4 text I need to concat some text v5 : v6 text I need to concat some text v7 : v8
CodePudding user response:
I would break this out a bit more.
Make a loop that can transform each item into a string and add it to a list.
Then join the final list using whatever delimiter you need.
Try something like this:
string_values = []
for value in list_of_tables.values():
if value:
val1, val2 = value.split(':')
string_value = gen_stmt(val1, val2)
string_values.append(string_value)
print(' text I need to concat '.join(string_values))
To skip the first value, you can turn the values object into a list, and then slice off the first value:
And a one liner just for kicks:
print(' text I need to concat '.join(
gen_stmt(*value.split(':'))
for value in list_of_tables.values()
if value
))
CodePudding user response:
You can also pass a if-else statement which will filter first value from other elements of list. my suggested code is like this.
list_of_tables = {'k1': 'v1:v2',
'k2':'v3:v4',
'k3':'v5:v6',
'k4':'v7:v8',
'k5':None }
def gen_stmt(val1_name, val2_name):
return 'some text ' val1_name ':' val2_name
fin_value = ''
i = 0
for k,v in list_of_tables.items():
if i == 0:
pair_val = v.split(':')
fin_value = gen_stmt(*pair_val) " "
elif v:
pair_val = v.split(':')
fin_value = 'text I need to concat' gen_stmt(*pair_val)
i =1
print(fin_value)
I think this very simple method but yes some extra line here added which make your code little bit long.