Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

Creating Lists from CSV files Python

I have a list of strings. I now want to create a list for each string within my original list. I don't want to hard code in the new lists.

For example if my list is my_list = ['Paul', 'Ringo', 'John', 'George'] I want to create 4 new lists, one for each string (Paul = [ ] Ringo = [ ] etc). Any ideas? Thanks!

question from:https://stackoverflow.com/questions/66055422/creating-lists-from-csv-files-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot dynamically name variables on run time with Python. However, you could fill a dictionary where the keys are the items from the list and the values are an empty list. Like this:

my_list = ['Paul', 'Ringo', 'John', 'George']
my_dict = {}

for name in my_list:
    my_dict[name] = []

print(my_dict)
# {'Paul': [], 'Ringo': [], 'John': [], 'George': []}

For bonus, you can use dictionary comprehension which is way shorter. Like this:

my_list = ['Paul', 'Ringo', 'John', 'George']
my_dict = {item:[] for item in my_list}

print(my_dict)
# {'Paul': [], 'Ringo': [], 'John': [], 'George': []}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...