简体   繁体   中英

Python list comprehension modify the elements based on string match

I have python code which return the list comprehension as shown below in return code.

return [str(source.get(field)) for field in fields]
# one of the list output
['3', 'checkuser', '=checkuser', 'management', '', 'checkuser@gmail.com', '', 'True', "['apiusermanagement']", 'False']

Requirement

I need to check each element in list and if element first character is starting with any of ('=', '@', '|', '%') these characters then I need to append the single double quote (") in starting of that list element.

For example, 3rd element '=checkuser' in example output started with '=' so this element should be modified as '"=checkuser' and same should be part of returned list output

# Expected output
['3', 'checkuser', '"=checkuser', 'management', '', 'checkuser@gmail.com', '', 'True', "['apiusermanagement']", 'False']

I am beginner in Python and try to achieve this with minimal changes & good performance output. Any help or pointer would be much appreciated

One option would be to put this logic into a function:

def fetch_and_map(field):
    result = str(source.get(field))
    if result.startswith("="):
        return '"' + result
    else:
        return result

return [fetch_and_map(field) for field in fields]

You could also do this inline as:

return ['"' + str(source.get(field)) if str(source.get(field)).startswith("=") else str(source.get(field)) for field in fields]

Note that if source is a dict of strings, you can make this simpler by skipping the str() call:

return ['"' + source.get(field) if source.get(field).startswith("=") else source.get(field) for field in fields]

You can use this code:

output = ['3', 'checkuser', '=checkuser', 'management', '', 'checkuser@gmail.com', '', 'True', "['apiusermanagement']", 'False']
output_modified = []
for string in output:
    if string != "" and string[0] in ['=', '@', '|', '%']:
        output_modified.append('"' + string)
    else:
        output_modified.append(string)

This will iterate over each string in output . If the string is not empty and begins with '=' , '@' , '|', or '%' , it will add '"' to the beginning of string and append it to output_modified . If not, it will simply append it to output_modified as-is.

Put the list in a variable. Then loop over the variable, adding the double quote where needed.

result = [str(source.get(field)) for field in fields]
for i, val in enumerate(result):
    if len(val) > 0 and val[0] in ('=', '@', '|', '%'):
        result[i] = '"' + val
return result

something like this

lst = ['3', 'checkuser', '=checkuser', 'management', '', 'checkuser@gmail.com', '', 'True', "['apiusermanagement']",
       'False']
lst_ex = [f'"{x}' if x and x[0] in {'=', '@', '|', '%'} else x for x in lst]
print(lst_ex)

output

['3', 'checkuser', '"=checkuser', 'management', '', 'checkuser@gmail.com', '', 'True', "['apiusermanagement']", 'False']

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