简体   繁体   中英

Manipulating elements in a Python List

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.

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.

您还可以尝试range方法 -

[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))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM