2013-02-16 46 views
1

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

+2

您的代码中随机选择线和消除* *它们。 – 2013-02-16 22:40:05

回答

3
import random 

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

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

print "\nFalling:\n"+'.\n'.join(picked)+'.' 
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] 
+0

'randint'是'a <= b <= c'。 – Amber 2013-02-16 22:44:55

+0

@Amber:是的,谢谢。 – Blender 2013-02-16 22:45:29

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.shuffle'就地(我不知道为什么)。它返回'None'。 – Blender 2013-02-16 22:45:54

+0

这是一个就地算法..这是最有效的方法。如果您需要原始列表,只需在洗牌之前创建副本即可。 – 2013-02-16 23:08:58

+0

你的解决方案没有意义。 'while True:'循环只会将's'设置为列表。它只在循环后打印'random.shuffle(s)'。但是,循环永远不会结束,因为没有'break'子句。 – 2013-02-16 23:09:14

1

您可以使用random.sample挑选的随机数您的清单中的项目。

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