在Python中随机化/随机播放列表/数组?

时间:2013-02-16 22:37:29

标签: python random shuffle

我是Python新手,没有编程经验。我有这个(我不确定它是列表还是数组):

from random import choice
while True:
s=['The smell of flowers',
'I remember our first house',
'Will you ever forgive me?',
'I\'ve done things I\'m not proud of',
'I turn my head towards the clouds',
'This is the end',
'The sensation of falling',
'Old friends that have said good bye',
'I\'m alone',
'Dreams unrealized',
'We used to be happy',
'Nothing is the same',
'I find someone new',
'I\'m happy',
'I lie',
]
l=choice(range(5,10))
while len(s)>l:
s.remove(choice(s))
print "\nFalling:\n"+'.\n'.join(s)+'.'
raw_input('')

随机选择5-10行并打印出来,但它们以相同的顺序打印;即如果被选中,“我撒谎”将始终位于底部。我想知道如何将所选行重新排列,以便它们以更随机的顺序出现?

编辑: 所以当我尝试运行时:

import random
s=['The smell of flowers',
'I remember our first house',
'Will you ever forgive me?',
'I\'ve done things I\'m not proud of',
'I turn my head towards the clouds',
'This is the end',
'The sensation of falling',
'Old friends that have said good bye',
'I\'m alone',
'Dreams unrealized',
'We used to be happy',
'Nothing is the same',
'I find someone new',
'I\'m happy',
'I lie',
]

picked=random.sample(s,random.randint(5,10))
print "\nFalling:\n"+'.\n'.join(picked)+'.'

它似乎运行,但不打印任何东西。我是否从Amber的答案中正确输入了这个?我真的不知道我在做什么。

4 个答案:

答案 0 :(得分:3)

import random

s = [ ...your lines ...]

picked = random.sample(s, random.randint(5,10))

print "\nFalling:\n"+'.\n'.join(picked)+'.'

答案 1 :(得分:2)

您还可以使用random.sample,它不会修改原始列表:

>>> import random
>>> a = range(100)
>>> random.sample(a, random.randint(5, 10))
    [18, 87, 41, 4, 27]
>>> random.sample(a, random.randint(5, 10))
    [76, 4, 97, 68, 26]
>>> random.sample(a, random.randint(5, 10))
    [23, 67, 30, 82, 83, 94, 97, 45]
>>> random.sample(a, random.randint(5, 10))
    [39, 48, 69, 79, 47, 82]

答案 2 :(得分:1)

这是一个解决方案:

    import random
    s=['The smell of flowers',
    'I remember our first house',
    'Will you ever forgive me?',
    'I\'ve done things I\'m not proud of',
    'I turn my head towards the clouds',
    'This is the end',
    'The sensation of falling',
    'Old friends that have said good bye',
    'I\'m alone',
    'Dreams unrealized',
    'We used to be happy',
    'Nothing is the same',
    'I find someone new',
    'I\'m happy',
    'I lie',
    ]
    random.shuffle(s)
    for i in s[:random.randint(5,10)]:
        print i

答案 3 :(得分:1)

您可以使用random.sample从列表中选择随机数量的项目。

import random
r = random.sample(s, random.randint(5, 10))