Python如何基于用户输入数量动态生成N个层级分类列表?
动态生成自定义数量层级列表的实现
功能需求
- 支持用户自主选择层级数量N,将导入的电影、游戏等条目划分为N个层级
- 每个层级内的条目两两配对供用户选择偏好内容,分层可大幅降低全量配对的运算量
- 实现逻辑:先给每个条目打1~N的分值,再按分值拆分到对应层级的独立列表中
现有实现瓶颈
固定层级数量时可提前声明对应数量的空列表,按分值追加条目即可。但层级数量由用户自定义的场景下,无法提前创建对应数量的空列表,也不知道如何将不同分值对应的条目组存入独立的列表变量。
原有相关代码
def scores(my_games): global NumT global big_dict big_dict = {} NumT = input("How many tiers would you like to divide the list into? \n" "Fewer tiers will result in more battles. \n" "It is recommended to use between 2 and 5 tiers.") while NumT.isdigit() == False: print("Oops! That was not a number. Try again...") NumT = input("Choose a number of tiers") NumT = int(NumT) print(NumT) print(f'For each game give it a score of between 1 and {NumT} to divide the games into {NumT} tiers') for item in my_games: score = (input(f' Score 1 - {NumT}: {item}')) while score.isdigit() == False: print("Oops! That was not a number. Try again...") score = (input(f' Score 1 - {NumT}: {item}')) score = int(score) if score not in range (1, NumT+1, 1): print(f'That number is not between 1 and {NumT}. Try again....') score = int(input(f' Score 1 - {NumT}: {item}')) big_dict[item] = score def make_tiers(big_dict, NumT): print(NumT) for n in range (1, NumT+1): print(n) keys = [k for k, v in big_dict.items() if v == n] print(keys)
原有代码说明:scores函数运行正常,将条目和对应分值存储在字典中(条目为key,分值为value);make_tiers函数已实现按分值提取对应条目的逻辑,但无法将每组条目存入独立的列表变量。
可行解决方案
通过操作全局变量命名空间动态生成列表变量,实现代码如下:
def make_tiers(big_dict, NumT): print(NumT) for n in range (1, NumT+1): print(n) keys = [k for k, v in big_dict.items() if v == n] globals()["list"+str(n)] = keys
该方案可动态生成list1、list2...listN共N个列表,分别存储对应分值的所有条目,满足自定义层级的需求。
内容的提问来源于stack exchange,提问作者MWallace
相关产品推荐
相关产品推荐

