Skip to main content
 首页 » 编程设计

python之将列表转换为列表python中的随机列表

2024年11月01日12bhlsheji

让我们想象一下,在 python 中我们有数字列表,如下所示:

[1, 3, 4, 5, 6, 7, 8, 9] 

将这个数字列表转换为列表中的随机列表序列的最简单方法是什么?

像这样:

[[1, 2, 3], [4], 5, 6, [7, 8], 9] 

请您参考如下方法:

使用 random.randint :

import random 
 
def random_series(lst, size=3): 
    start = end = 0 
    n = len(lst) 
    while end < n: 
        end += random.randint(1, size) 
        if end - start == 1: 
            yield lst[start] 
        else: 
            yield lst[start:end] 
        start = end 

示例用法:

>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] 
>>> list(random_series(lst)) 
[[1, 2, 3], 4, 5, [6, 7], [8, 9]] 
>>> list(random_series(lst)) 
[[1, 2], [3, 4], [5, 6], 7, 8, 9] 
>>> list(random_series(lst)) 
[[1, 2], [3, 4, 5], [6, 7], [8, 9]] 
>>> list(random_series(lst)) 
[[1, 2, 3], [4, 5, 6], 7, [8, 9]]