Creating Multiple Variables from a List of Strings
Given a list of strings like:
names = ['apple', 'orange', 'banana']
You may want to create a list associated with each string, named exactly like the string:
apple = [] orange = [] banana = []
How to Achieve This in Python
To accomplish this task, you can employ the following approach:
Create a dictionary using list comprehension:
fruits = {k:[] for k in names}
This creates a dictionary where each key corresponds to a string in names, and each value is an empty list.
Access the list associated with a particular string using the dictionary key:
fruits['apple']
This returns the empty list associated with the string 'apple'.
Note:
It's generally better to use a dictionary rather than creating separate variables for each string, as it provides flexibility and easy access to the data associated with each string.
The above is the detailed content of How to Create Multiple Variables from a List of Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!