• 周四. 3月 28th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

使用Python中的频率列表创建列表

[db:作者]

3月 7, 2023
age = [19, 20, 21, 22, 23, 24, 25]
frequency = [2, 1, 1, 3, 2, 1, 1]
output_age = [19, 19, 20, 21, 22, 22, 22, 23, 23, 24, 25]

我们如何创建一个新列表,根据另一个列表多次添加一个列表中的项目?在

谢谢

Tags:

项目列表outputagefrequency3条回答网友

1楼 ·

编辑于 2023-03-07 00:10:43

使用列表理解:

output_age = [i for l in ([a]*f for a, f in zip(age, frequency)) for i in l]
#[19, 19, 20, 21, 22, 22, 22, 23, 23, 24, 25]

为什么?

我们首先zipage和{}列表放在一起,这样我们就可以一致地迭代它们。因此:

^{pr2}$

给出:

19 2
20 1
21 1
22 3
23 2
24 1
25 1

然后我们要重复每个元素,a,重复次数由f决定。这可以通过创建一个列表并将其相乘来完成。就像:

[4] * 3
#[4, 4, 4]

然后我们需要解压这些值,这样我们就把这个表达式包装在一个生成器中(用括号表示)并在上面迭代。这会使列表变平。注意,有alternative ways来实现这一点(例如使用itertools.chain.from_iterable)。在


另一种方法是通过迭代一个range对象来重复这个数字a,而不是通过乘以一个列表来获得重复次数。在

此方法类似于:

output_age = [a for a, f in zip(age, frequency) for _ in range(f)]
#[19, 19, 20, 21, 22, 22, 22, 23, 23, 24, 25]

网友

2楼 ·

编辑于 2023-03-07 00:10:43

下面是一个使用ziprange的解决方案

>>> age = [19, 20, 21, 22, 23, 24, 25]
>>> frequency = [2, 1, 1, 3, 2, 1, 1]
>>> [a for a,f in zip(age, frequency) for _ in range(f)]
[19, 19, 20, 21, 22, 22, 22, 23, 23, 24, 25]

网友

3楼 ·

编辑于 2023-03-07 00:10:43

使用itertoolszip

例如:

from itertools import chain
age = [19, 20, 21, 22, 23, 24, 25]
frequency = [2, 1, 1, 3, 2, 1, 1]

print( list(chain.from_iterable([[i] * v for i,v in zip(age, frequency)])) )

输出:

^{pr2}$

  • 注意:chain.from_iterable将列表展平。在

《使用Python中的频率列表创建列表》有5个想法
  1. I loved even more than you will get done right here. The picture is nice, and your writing is stylish, but you seem to be rushing through it, and I think you should give it again soon. I’ll probably do that again and again if you protect this walk.

  2. I just could not depart your web site prior to suggesting that I really loved the usual info an individual supply in your visitors Is gonna be back regularly to check up on new posts

  3. of course like your website but you have to check the spelling on several of your posts A number of them are rife with spelling issues and I in finding it very troublesome to inform the reality on the other hand I will certainly come back again

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注