Home >Backend Development >Python Tutorial >How Can I Return a Predefined List in Python Based on String Input?

How Can I Return a Predefined List in Python Based on String Input?

DDD
DDDOriginal
2024-12-18 22:04:15355browse

How Can I Return a Predefined List in Python Based on String Input?

Returning a Pre-determined Value Based on String Input

In Python, we sometimes encounter the need to return a specific list based on a provided string. This can be achieved using various methods, one of which involves leveraging dictionaries.

Using a Dictionary

The most straightforward approach is to define a dictionary where keys represent the string inputs and corresponding values are the desired lists.

get_ext = {'text': ['txt', 'doc'],
            'audio': ['mp3', 'wav'],
            'video': ['mp4', 'mkv']
}

To retrieve the desired list, simply access the appropriate key:

get_ext['video']
# Output: ['mp4', 'mkv']

Using a Function with the Dictionary

If prefer a function-based solution, you can assign the get method of the dictionary to a variable:

get_ext = get_ext.get

This function will return the list for the specified key or None if the key doesn't exist.

get_ext('video')
# Output: ['mp4', 'mkv']

Using a Custom Default Value

To specify a custom default value for unknown keys, consider using a wrapper function:

def get_ext(file_type):
    types = {'text': ['txt', 'doc'],
             'audio': ['mp3', 'wav'],
             'video': ['mp4', 'mkv']
    }

    return types.get(file_type, [])

This function will return an empty list for unknown keys.

Addressing Performance Concerns

For performance-conscious applications, it's worth noting that the types dictionary in the wrapper function is recreated every time the function is called. To optimize this, you can create a class and initialize the types dictionary within the constructor, ensuring it's only created once.

class get_ext(object):
    def __init__(self):
        self.types = {'text': ['txt', 'doc'],
                      'audio': ['mp3', 'wav'],
                      'video': ['mp4', 'mkv']
        }

    def __call__(self, file_type):
        return self.types.get(file_type, [])

get_ext = get_ext()

This class-based approach enables easy modification of the recognized file types while maintaining performance efficiency.

The above is the detailed content of How Can I Return a Predefined List in Python Based on String Input?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn