如何在Python中生成指定结构的嵌套列表?
问题描述
现有两个Python列表:
my_list = ['hat', 'bat'] other_list = ['A', 'B', 'C']
需要生成嵌套列表,预期结果为:
new_list = ['hat',['bat_A', 'bat_B', 'bat_C']]
即遍历other_list,将'bat'与其中每个元素拼接成bat_元素的形式,放入嵌套列表中,同时保留'hat'作为普通元素。
尝试了以下代码,但得到错误结果['hat', 'hat', 'hat', ['bat_A', 'bat_B', 'bat_C']]:
new_list = [] extra = [] for item in other_list: for thing in my_list: if thing == 'bat': extra.append(thing + '_' + item) else: new_list.append(thing) new_list.append(extra)
问题原因
你的代码循环顺序错误:每次遍历other_list的一个元素时,都会完整遍历一次my_list,导致'hat'被重复添加了3次(对应other_list的3个元素),最后才把拼接好的extra列表追加进去,所以结果多出了两个'hat'。
解决方案
调整循环逻辑,先遍历my_list的元素,针对不同元素做对应处理:
方法一:普通循环写法
my_list = ['hat', 'bat'] other_list = ['A', 'B', 'C'] new_list = [] for thing in my_list: if thing == 'bat': # 生成bat与other_list元素拼接的子列表 bat_sub_list = [f"{thing}_{item}" for item in other_list] new_list.append(bat_sub_list) else: # 非bat元素直接添加 new_list.append(thing) print(new_list) # 输出: ['hat', ['bat_A', 'bat_B', 'bat_C']]
方法二:列表推导式(更简洁)
如果喜欢紧凑的写法,可以用嵌套列表推导式一次性生成结果:
my_list = ['hat', 'bat'] other_list = ['A', 'B', 'C'] new_list = [ [f"{t}_{i}" for i in other_list] if t == 'bat' else t for t in my_list ] print(new_list) # 输出: ['hat', ['bat_A', 'bat_B', 'bat_C']]
内容的提问来源于stack exchange,提问作者gwydion93
相关产品推荐
相关产品推荐

