gpt4 book ai didi

python - 函数参数中的动态变量

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:07 24 4
gpt4 key购买 nike

我正在尝试使用 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? .

关于python - 函数参数中的动态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53463077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com