python - 根据另一个列表中的值重复的连续数字列表

标签 python list

我的目标是获得一个连续数字的列表,并根据初始列表值相应地重复。假设我有:

initialList=[1,2,3,5]

我想得到:

targetList=[0,1,1,2,2,2,3,3,3,3,3]

...我是 Python 的新手,对于这个 - 可能 - 非常第一步的问题,我深表歉意。不幸的是,尝试了很多搜索,但结果与我的需求不符。非常感谢您。

最佳答案

新手友好的解决方案是使用两个循环:

result = []
number = 0
for repeat in initialList:
    for _ in range(repeat):
        result.append(number)
    number += 1

print(result)  # [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3]

如果出于任何原因您更喜欢单行,您可以结合 enumeraterange得到

result = [num for num, repeat in enumerate(initialList) for _ in range(repeat)]

关于python - 根据另一个列表中的值重复的连续数字列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49613360/

相关文章:

python - 切片列表以获得相同长度的四分之一

python - 当我使用 operator[] 时列出导致错误的项目

c# - 字典与列表与数组的速度和功能

python - 对 python 列表中的相关值求和

python - 亚马逊 Elastic Beanstalk : how to set the wsgi path?

Python 交替引用新实例

python - 了解 python asyncio 协议(protocol)

r - purrr:modify2 和 modify_at

python - 所需代码的说明 : Appending the values to list in python

python - 在 Python 中嵌套三元运算符