【问题标题】:convert list into random list within list python将列表转换为列表python中的随机列表
【发布时间】:2014-02-16 09:53:30
【问题描述】:

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

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

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

像这样:

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

【问题讨论】:

  • 它必须保持“排序”吗?
  • 2 在您的输入中丢失?还是将其添加到输出列表中?

标签: python list indexing


【解决方案1】:

使用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]]

【讨论】:

  • +1。请也查看我的回答,如果可以,请告诉我。
  • @ComputerFellow 复制您的评论。 :)
  • @ComputerFellow, rand_series 在您的代码中修改原始列表。这可能会导致问题取决于具体情况。
  • @ComputerFellow,该功能也不保留顺序。但是 OP 没有具体说明;这可能不是问题。
  • @falsetru 哇。谢谢。我看看能不能让它更优雅一点!
【解决方案2】:

我的代码(我假设2 在输入列表中):

from random import randint

L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print L
l, length = 0, len(L)
L2 = []
while l < length:
    r = randint(0, length - l)  # rnum < length_remaining  
    x = L[l: l + r] # taking next `r`  numbers from original L 
    if len(x) > 1:   
        L2.append(x)  # append as list        
    if len(x) == 1:
        L2.append(x[0]) # append as single element 
    l += r    
print L2

一些执行:

$ python  x.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[[1, 2, 3, 4], 5, [6, 7, 8], 9]
$ python  x.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[[1, 2, 3, 4], [5, 6, 7, 8, 9]]
$ python  x.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[[1, 2, 3, 4, 5, 6], [7, 8], 9]
$ python  x.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, [2, 3], 4, [5, 6], [7, 8], 9]

不是很多,但有点改善:

L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print L
l, length = 0, len(L)
L2 = []
while l < length:
    r = randint(1, length - l)  # rnum < length_remaining  
    x = L[l: l + r] # taking next `r`  numbers from original L 
    if len(x) > 1:   
        L2.append(x)  # append as list        
    else:
        L2.extend(x) # append as single element 
    l += r    
print L2

【讨论】:

  • 如果有人发现错误,也请添加评论。这对我会有帮助。
猜你喜欢
  • 2016-07-05
  • 2018-01-17
  • 2022-11-23
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多