如何判断元组列表含重复字符串并返回重复项中int值更高的元组
代码存在的问题
- 变量引用错误:代码中写了
tup[1],但遍历输入时你将元组赋值给了var,根本没有定义tup变量,运行直接触发NameError。 - 核心逻辑缺失:没有对相同类型的元组做筛选取最大值的处理,当前代码会把所有输入元组对应的元素全部拼接,比如第一个测试用例两个
int元组会生成3+5=8个1,和预期的5个完全不符。 - 循环变量重名:外层遍历输入的变量名是
i,内层循环生成元素的变量名也用了i,属于不规范写法,容易引发未知逻辑错误。
修改方案
首先先遍历所有输入元组,记录每个类型对应的最大数值,再按照数值从大到小的顺序拼接生成结果列表,就能匹配预期输出。
修正后代码
def generate_combined_list(inputs: list): data_types = {'set': set(), 'list': [], 'dict': {}, 'int': 1, 'float': 1.5, 'string': 'poodle'} type_max_count = {} # 遍历统计每个类型的最大数量 for count, typ in inputs: if typ not in data_types: continue if typ not in type_max_count or count > type_max_count[typ]: type_max_count[typ] = count # 按数量从大到小排序后生成结果 new_list = [] for typ, count in sorted(type_max_count.items(), key=lambda x: -x[1]): new_list.extend([data_types[typ]] * count) return new_list
测试验证
print(generate_combined_list([(3, 'int'), (5, 'int')])) # 输出 [1, 1, 1, 1, 1],符合预期 print(generate_combined_list([(3, 'int'), (5, 'list'), (4, 'int')])) # 输出 [[], [], [], [], [], 1, 1, 1, 1],符合预期
内容的提问来源于stack exchange,提问作者moll koll
相关产品推荐
相关产品推荐

