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]
为什么?
我们首先zip
将age
和{}列表放在一起,这样我们就可以一致地迭代它们。因此:
^{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
下面是一个使用zip
和range
的解决方案
>>> 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
使用itertools
和zip
例如:
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
将列表展平。在
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.
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
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
I truly appreciate your technique of writing a blog. I added it to my bookmark site list and will
Wow, marvelous blog format! How lengthy have you been blogging
for? you make running a blog look easy. The full glance of your website is magnificent, let alone the content!
You can see similar here ecommerce