2013-02-16 83 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))