Skip to main content
 首页 » 编程设计

python之在 Python 中随机化/随机排列列表/数组

2025年05月04日13lautakyan007

我是 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 的回答中正确输入了这个?我真的不知道我在做什么。

请您参考如下方法:

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