Reputation: 127
I have a strange requirement where I need to manipulate the contents of a list based on certain rules.
My list is as below:
lst = [
'%s###timestamp',
"TRANSLATE(%s, ',', '')###sales",
"TRANSLATE(%s, ',', '')###units",
"TRANSLATE(%s, ',', '')###counting_units",
"TRANSLATE(%s, ',', '')###standard_units"]
As per the requirement, every '%s' has to be replaced by 'SPLIT(expld ' and the final result has to be like below:
res = [
"""SPLIT(expld, "###")[0] AS timestamp""",
"""TRANSLATE(SPLIT(expld, "###")[1], ',', '') AS sales""",
"""TRANSLATE(SPLIT(expld, "###")[2], ',', '') AS units""",
"""TRANSLATE(SPLIT(expld, "###")[3], ',', '') AS counting_units""",
"""TRANSLATE(SPLIT(expld, "###")[4], ',', '') AS standard_units"""]
where [0],[1],[2] and so on represents the index of the list.
Why I need to create the 'res' like this because I need this list later to construct a Hive Query.
In my attempt so far, I have just been able to replace '%s' value with 'SPLIT(expld ' which was straightforward.
splitExpr = [w.replace('%s', 'SPLIT(expld ') for w in lst]
I'm still trying to figure out how can I get the desired result in this case.
Upvotes: 1
Views: 86
Reputation: 3669
You could also try a range
method -
[x[i].replace("TRANSLATE(%s, ',', '')###", "TRANSLATE(SPLIT(expld, \"###\"[{}],',', '') AS ".format(i)) if "TRANSLATE" in x[i] else x[i].replace("%s###","SPLIT(expld, \"###\")[{}] AS ".format(i)) for i in range(len(x))]
Upvotes: 0
Reputation:
res = [w.replace('###', ' AS ').replace('%s', 'SPLIT(expld, "###")[{}]'.format(i)) for i, w in enumerate(lst)]
Use the enumerate function to get the index and string simultaneously. I also replaced '###' with ' AS ' before the split you suggested.
List comprehensions like this one are concise but you might consider using a regular for loop for more readable code.
Upvotes: 3