根据另一个列表中的元素数量创建包含重复项的列表

问题描述 投票:0回答:2

我在创建/思考如何解决这个问题时遇到了一些问题。 我需要有 2 个列表。 1 是“用户”列表,另一个是“人口”列表。 对于“人口”中的每一项,我需要重复“用户”列表中的每一项。 例子:

人口 用户
1 AA
2 AA
3 AA
1 BB
2 BB
3 BB

现在,我得到这样的数据

User_list = [AA,BB]
Population_list = [1,2,3]

任何帮助都会很好,提前致谢!

python list repeat
2个回答
1
投票

请参阅上面@Mathpdegeek497 的评论:您需要按照您打算获得输出的顺序遍历两个列表。

注意,我假设你的意思是用户 AA 和 BB 是字符串,所以你需要在它们周围加上引号。如果它们是 not 字符串,并且表示以前存储的变量,则不需要引号。

代码:

populations = [1, 2, 3]
users = ['AA', 'BB']

for user in users:
    for pop in populations:
        print(f"{pop} {user}")

输出:

1 AA
2 AA
3 AA
1 BB
2 BB
3 BB

1
投票

带代码的逻辑:

#from the specs you have written, it seems you just need to repeat each element of  user_list that number of times
population = [1,2,3]
pop_length = len(population) #find the length of population
users_list = ['AA','BB'] 
final_list = []
for user in users_list:
    final_list.extend([user]*pop_length)

final_list #yields ['AA', 'AA', 'AA', 'BB', 'BB', 'CC']
© www.soinside.com 2019 - 2024. All rights reserved.