2016-11-29 50 views
0

我正在編寫一個程序來隨機生成辦公室尋寶團隊的程序,因此我正在組織所以我編寫了這個簡單的代碼來模擬從帽子中挑選姓名,但只有更公平,但不完全知道爲什麼它不工作,它不返回所有的名字,比如我輸入了6名進入名單,但它只返回其中的4個這樣的:通過列表中的值隨機生成一組人羣

Group 1 consists of; 
Chris 
Ryan 
Paul 
Group 2 consists of; 
Alex 

我不在清除列表中的元素方面有很多經驗,所以它可能只是我做錯了。任何見解都會有所幫助。

import random 
participants=["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul"] 
group=1 
membersInGroup=3 

for participant in participants: 
    if membersInGroup==3: 
     print("Group {} consists of;".format(group)) 
     membersInGroup=0 
     group+=1 
    person=random.choice(participants) 
    print(person) 
    membersInGroup+=1 
    participants.remove(str(person)) 
+0

的可能的複製[德爾的區別,刪除和彈出列表上(http://stackoverflow.com/questions/11520492/del-remove-and-pop-on-lists之間的差異) –

回答

1

這個問題發生,因爲你是變異的列表在遍歷它。有幾個選擇來解決這個問題。需要對現有代碼和思考過程進行很少修改的一種選擇是對列表的副本進行變異,例如, participants[:]進行復制。

使用代碼:

import random 
participants=["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul"] 
group=1 
membersInGroup=3 

for participant in participants[:]:    # only modification 
    if membersInGroup==3: 
     print("Group {} consists of;".format(group)) 
     membersInGroup=0 
     group+=1 
    person=random.choice(participants) 
    print(person) 
    membersInGroup+=1 
    participants.remove(str(person)) 

輸出示例:

Group 1 consists of; 
Alex 
Paul 
Chris 
Group 2 consists of; 
Kimani 
Elsie 
Elise 
Group 3 consists of; 
Ryan 
+1

謝謝,這實際上是非常有意義的,它的小事情,這大大改變了事情 – WhatsThePoint

2

雖然pylangs' answer就足夠了,這是解決問題的另一種方法:

import random 
members = 3 
participants=["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul"] 
random.shuffle(participants) 
for i in range(len(participants) // members + 1): 
    print('Group {} consists of:'.format(i + 1)) 
    group = participants[i*members:i*members + members] 
    for participant in group: 
     print(participant) 
+0

一個有趣的方法@mohammad。 +1 – pylang

0

這取決於列表的類型。該代碼有行問題

for participant in participants:

而是使用

for participant in participants[:]: