如何基于另一个列表的元素数量生成含重复项的列表
解决方案
要生成你需要的关联列表,核心逻辑是为每个用户匹配所有人口数值,用嵌套循环就能实现。以下是具体的Python实现方案:
修正输入格式
首先注意你的输入里AA和BB是字符串,需要加上引号,否则会被当作未定义变量:
User_list = ["AA", "BB"] Population_list = [1, 2, 3]
生成关联列表
基础嵌套循环写法
# 初始化空列表存储结果 result = [] # 外层遍历用户列表,内层遍历人口列表 for user in User_list: for pop in Population_list: # 将每对组合以字典形式存入结果列表 result.append({"Population": pop, "Users": user}) # 按表格格式输出 print("| Population | Users |") print("|------------|-------|") for item in result: print(f"| {item['Population']:<10} | {item['Users']:<5} |")
简化的列表推导式写法
如果追求简洁,可以用列表推导式一行生成结果:
result = [{"Population": pop, "Users": user} for user in User_list for pop in Population_list]
输出结果
运行代码后会得到你需要的表格:
| Population | Users |
|---|---|
| 1 | AA |
| 2 | AA |
| 3 | AA |
| 1 | BB |
| 2 | BB |
| 3 | BB |
内容的提问来源于stack exchange,提问作者Cbot
相关产品推荐
相关产品推荐

