python – 函数参数的Dinamically var

我正在尝试使用var的名称来调用函数,但我不知道这是否可行,类似于:

fight_movies = list() # var how I want to use in function call
win_movies = list() # var how I want to use in function call
knowledge_movies = list() # var how I want to use in function call
biography_movies = list() # var how I want to use in function call

for genre in genres:
    .... Ommited #\/\/\/\/\/\/ Here is where I call the function
    write_jsonl(genre + '_movies', genre, rating, title, genre) #here is the call of the function


def write_jsonl(movie_list, genre, rating, title, json_name):
    dict = {'title': title, 'genre': genre, 'rating': rating}
    movie_list.append(dict)
    # print(action_movies)
    with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
        writer.write(movie_list)

我正在尝试动态地将变量名称作为列表传递,但我不确定在python中是否可以使用任何建议?

Error: Traceback (most recent call last):
  File "bucky.py", line 58, in <module>
    web_crawling()
  File "bucky.py", line 34, in web_crawling
    write_jsonl(genre + '_movies', genre, rating, title, genre)
  File "bucky.py", line 52, in write_jsonl
    movie_list.append(dict)
AttributeError: 'str' object has no attribute 'append'

最佳答案 只需使用字典:

genres_dict = {k: [] for k in ('fight', 'win', 'knowledge', 'biography')}

for genre in genres:
    write_jsonl(genres_dict[genre], genre, rating, title, genre)

可变数量的变量不是推荐的方法.

相关:How do I create a variable number of variables?.

点赞