在Python中随机/随机排列列表/数组?

2024-06-02 08:51:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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行并打印它们,但它们以相同的顺序打印;即“我撒谎”如果被选中,将始终位于底部。我想知道我怎样才能将选定的行随机排列,使它们以更随机的顺序出现?在

编辑: 所以当我试着运行这个程序时:

^{pr2}$

它似乎在运行,但不打印任何内容。我从Amber的答案中打对了吗?我真的不知道我在做什么。在


Tags: ofthefrom列表顺序is编程random
3条回答

您可以使用random.sample从列表中随机选择一个项目。在

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

您还可以使用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]
import random

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

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

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

相关问题 更多 >