让我们假设在python中我们有数字列表,如下所示:
[1, 3, 4, 5, 6, 7, 8, 9]
将这个数字列表转换为列表中的随机系列列表的最简单方法是什么?
像这样:
[[1, 2, 3], [4], 5, 6, [7, 8], 9]
答案 0 :(得分:2)
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 :(得分:0)
我的代码(我假设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