动态改变函数的参数

时间:2018-11-24 22:55:06

标签: python list

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

3 个答案:

答案 0 :(得分:2)

您可以像这样在locals() / globals()中找到变量

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

答案 1 :(得分:2)

大多数人建议使用字典,然后,如果我愿意,我认为打算将字典存储在列表中。但是,您的代码显示了一个问题,其中您为我希望成为列表的内容传递了一个字符串。

def write_jsonl(movie_list, genre, rating, title, json_name):
    d= {'title': title, 'genre': genre, 'rating': rating}
    movie_list.append(d) #<-- movie_list based on your traceback is a str
    # print(action_movies)
    with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
        writer.write(movie_list)

下面的示例按预期工作:

all_movie_list = []

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

write_jsonl(all_movie_list,'Crime','10','Godfather','test')

all_movie_list
[{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]

更好的方法是将按类型列出的标题列表存储在字典中,您可以为此使用Python标准库中的defaultdict数据模型。

from collections import defaultdict
movie_list = defaultdict(list)

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

movie_list
>>defaultdict(list,
            {'Crime_movies': [{'title': 'Godfather',
               'genre': 'Crime',
               'rating': '10'}]})

movie_list['Crime_movies']
>>[{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]

也不要使用内置方法或保留名称作为变量,我将dict变量替换为d

答案 2 :(得分:2)

只需使用字典:

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?