【问题标题】:How to turn repeating code in to functions when a while loop is used使用 while 循环时如何将重复代码转换为函数
【发布时间】:2018-03-30 22:50:54
【问题描述】:

我有一些极其重复的 Python 代码,我想将它们转换为一个函数,但我不确定其中的逻辑,因为它涉及到 while 循环。

#Get initial tracks for playlist and save to JSON file
tracks_file_count = 0
tracks_file_name = f'{str(tracks_file_count)}_tracks.json'
tracks_file = open(tracks_file_name,'w+')
tracks_response = requests.request('GET', 
  f'{config.global_url}/users/{user}/playlists/{playlist_id}/tracks',
  headers=headers
)
tracks_file.write(tracks_response.text)
tracks_file.close()
tracks_file = open(tracks_file_name,'r')
tracks = json.load(tracks_file)
#Save comma seperated track ID's to variable
id_dict = []
for i in tracks['items']:
    track_id = i['track']['id']
    id_dict.append(track_id)
id_comma = (','.join(id_dict))
#Get Audio Features
features_file_count = 0
features_file_name = f'{str(features_file_count)}_features.json'
features_file = open(features_file_name,'w+')
features_response = requests.request('GET', 
  f'{config.global_url}/audio-features/?ids={id_comma}', 
  headers=headers
)
features_file.write(features_response.text)
features_file.close()
features_file = open(features_file_name,'r')
features = json.load(features_file)
track_writer(tracks, playlist_id)
feature_writer(features, playlist_id)
next_url = tracks['next']



while next_url != None:
    tracks_file_count += 1
    tracks_file_name = f'{str(tracks_file_count)}_tracks.json'
    tracks_file = open(tracks_file_name,'w+')
    tracks_response = requests.request('GET', next_url, 
      headers=headers
    )
    tracks_file.write(tracks_response.text)
    tracks_file.close()
    tracks_file = open(tracks_file_name,'r')
    tracks = json.load(tracks_file)
    #Save comma seperated track ID's to variable
    id_dict = []
    for i in tracks['items']:
        track_id = i['track']['id']
        id_dict.append(track_id)
    id_comma = (','.join(id_dict))
    #Get Audio Features
    features_file_count += 1
    features_file_name = f'{str(features_file_count)}_features.json'
    features_file = open(features_file_name,'w+')
    features_response = requests.request('GET', 
      f'{config.global_url}/audio-features/?ids={id_comma}',
      headers=headers
    )
    features_file.write(features_response.text)
    features_file.close()
    features_file = open(features_file_name,'r')
    features = json.load(features_file)
    track_writer(tracks, playlist_id)
    feature_writer(features, playlist_id)
    next_url = tracks['next']    

链接到原始gist (编者注:缩进不是 100% 保留,换行)

在我的例子中,我首先用 0_ 命名我的文件,然后当条件不等于“无”时,我再次执行代码,但增加文件名,使其以 1_ 开头,依此类推。 URL 也会发生变化。这个

表明唯一的变化是递增 1 和 URL。

【问题讨论】:

  • 在此处发布您的代码,而不仅仅是在远程站点。
  • 欢迎来到 Stack Overflow。请使用tour 并阅读有关How to Ask 的信息,尤其是有关创建minimal reproducible example 的信息。
  • 不应该将next_url = tracks['next'] 缩进以使其在循环内吗?
  • 为什么你认为循环很难将代码放入函数中?
  • 谢谢@AndreyTyukin,现在一切都好。

标签: python python-3.x function while-loop dry


【解决方案1】:

只需将公共部分分解为一个函数即可:

def repetitiveStuff(tracks_file_count, next_url, features_file_count)
  tracks_file_name = f'{str(tracks_file_count)}_tracks.json'
  tracks_file = open(tracks_file_name,'w+')
  tracks_response = requests.request('GET', next_url, headers=headers)
  tracks_file.write(tracks_response.text)
  tracks_file.close()
  tracks_file = open(tracks_file_name,'r')
  tracks = json.load(tracks_file)
  #Save comma seperated track ID's to variable
  id_dict = []
  for i in tracks['items']:
    track_id = i['track']['id']
    id_dict.append(track_id)
  id_comma = (','.join(id_dict))
  #Get Audio Features
  features_file_name = f'{str(features_file_count)}_features.json'
  features_file = open(features_file_name,'w+')
  features_response = requests.request('GET', 
    f'{config.global_url}/audio-features/?ids={id_comma}', 
    headers=headers
  )
  features_file.write(features_response.text)
  features_file.close()
  features_file = open(features_file_name,'r')
  features = json.load(features_file)
  track_writer(tracks, playlist_id)
  feature_writer(features, playlist_id)
  return tracks['next']


#Get initial tracks for playlist and save to JSON file
next_url = repetitiveStuff(
  0,
  f'{config.global_url}/users/{user}/playlists/{playlist_id}/tracks',
  0
)

tracks_file_count = 0
features_file_count = 0

while next_url != None:
  tracks_file_count += 1
  features_file_count += 1
  next_url = repetitiveStuff(tracks_file_count, next_url, features_file_count)

请注意,现在标识符tracks_file_countnext_urlfeatures_file_count两次用作函数的参数和全局变量/循环变量。 next_url 现在由创建 tracks 字典的函数返回。

【讨论】:

  • 我可以确认这有效@Andrey,谢谢。没想到更新 next_url 的同时运行函数。
  • @Dan 不客气。是的,确实,花了一点时间来理解tracks['next'] 来自哪里以及它必须去哪里......
猜你喜欢
  • 2021-10-22
  • 2023-01-22
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 2012-06-25
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
相关资源
最近更新 更多