1

我对 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

4 回答 4

3
import random

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

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

print "\nFalling:\n"+'.\n'.join(picked)+'.'
于 2013-02-16T22:41:42.007 回答
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]
于 2013-02-16T22:44:30.923 回答
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
于 2013-02-16T22:45:03.460 回答
1

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

import random
r = random.sample(s, random.randint(5, 10))
于 2013-02-16T22:45:06.807 回答