gpt4 book ai didi

python - 使用 itertools 重复数字

转载 作者:行者123 更新时间:2023-12-01 21:46:02 25 4
gpt4 key购买 nike

我在学习 itertools 时遇到了一个有趣的问题。

如何得到下面的结果?

nums = [1,2,3,4]
# logic: i+1 th number is repeated i times.
2 is repeated 1 times and 4 is repeated 3 times.

required = [2,4,4,4]

我的尝试

import itertools

nums = [1,2,3,4]
nums[::2] # [1,3]
nums[1::2] # [2,4]
* 2 is repeated 1 times
* 4 is repeated 3 times and makes [2,4,4,4]

list(itertools.starmap(itertools.repeat, zip(nums[::2],nums[1::2])))

Gives,
[repeat(1, 2), repeat(3, 4)]

How to get:
required = [2,4,4,4]

必需

From: [1,2,3,4]
To: [2,4,4,4]

We can use itertools, list comp and numpy.
With emphasis on itertools, since I am learning itertools functions
such as repeat, starmap and so on.

最佳答案

repeat 创建一个可迭代对象,因此您需要将这些迭代器链接在一起,然后再通过迭代结果创建列表。 (您还需要将参数交换为 zip)

>>> from itertools import starmap, repeat, chain
>>> list(<b>chain.from_iterable(</b>starmap(repeat, zip(nums[<b>1</b>::2], nums[::2]))<b>)</b>)
[2, 4, 4, 4]

实际上,您不需要starmapzipmap 可以将多参数函数应用于多个迭代器,每次调用从每个迭代器获取一个参数。

>>> list(chain.from_iterable(map(repeat, nums[1::2], nums[::2])))
[2, 4, 4, 4]

itertools 领域更进一步,您可以使用 teeislice 来避免通过切片 创建两个临时列表>nums(虽然在一行中这样做会变得困惑):

>>> from itertools import tee, islice
>>> t1, t2 = tee(nums)
>>> list(chain.from_iterable(map(repeat, <b>islice(t1, 1, None, 2)</b>, <b>islice(t2, None, None, 2)</b>)))
[2, 4, 4, 4]

关于python - 使用 itertools 重复数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60566858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com