如何在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行并打印出来,但它们的顺序是固定的;比如说“我撒谎”如果被选中,总是会在最后一行。我想知道怎么才能打乱这些选中的行,让它们以更随机的顺序出现?
编辑:
所以当我尝试运行这个代码:
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 个回答
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
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]
3
在编程中,有时候我们需要把一些复杂的东西简化,方便我们理解和使用。比如说,代码中的某些部分可能会让人觉得很难懂,这时候我们就需要找到一种更简单的方式来表达它。
有些时候,程序的运行速度可能会受到影响,这可能是因为代码写得不够高效。我们可以通过优化代码来提高它的运行速度,让程序运行得更流畅。
另外,调试也是编程中很重要的一部分。调试就是找出代码中的错误并修复它们。这个过程可能会让人感到沮丧,但它是学习编程过程中必不可少的一环。
总之,编程就像是解谜一样,我们需要不断地尝试和学习,才能把这些复杂的概念变得简单易懂。
import random
s = [ ...your lines ...]
picked = random.sample(s, random.randint(5,10))
print "\nFalling:\n"+'.\n'.join(picked)+'.'