2017-09-22 42 views
0

我有一些使用戶在列表中添加單詞的代碼。假設用戶添加了5個單詞。 lst = ['The','first','letter','word''yes'],我們需要從列表中打印3個隨機單詞,但可能不一樣。因此,當我使用隨機模塊並打印2個相同的單詞時,它將替換其中的一個單詞,並且如果它再次打印相同的單詞,則會立即替換它。這是我的代碼,希望你能理解它。代碼需要在*所在的位置。如何替換附加但隨機模塊的雙列表項?

import random 

print('You can choose from randnormal and normextra.') 
print('Randnormal is a one time thing, so it can be that some people are showed twice,') 
print("but at randspecial people can't be chosen twice, so choose one") 
choose = input("randspecial(S) or randnormal(N): ") 
breaksystem = '1' 
while True: 
    def again(): 
     print() 
     _again_ = input('Do you want to do this again (Y/N): ') 
     if _again_.lower() == 'y': 
      print() 
     elif _again_.lower() == 'n': 
      breaksystem = '0' 
     else: 
      print('Try again:') 
      print() 
      again() 

    def randnormal(): 
     ppl = int(input('From how many people do you want to choose: ')) 
     print() 
     lst = [] 
     for i in range(0, ppl): 
      inp = input('Name of the person: ') 
      lst.append(inp) 

     many = int(input('How many people do you want to select: ')) 
     if many == 1: 
      print(random.choice(lst)) 
      again() 
     elif ppl < many: 
      print('You want to select more people than you have chosen.\n') 
      again() 
     else: 
      for i in range(0, many): 
       rand = random.randint(0, len(lst) - 1) 
       print(lst[rand]) 
      again() 

    def randspecial(): 
     ppl_ = int(input('From how many people do you want to choose: ')) 
     print() 
     lst_ = [] 
     for i in range(0, ppl_): 
      rand_ = input('Name of the person: ') 
      lst_.append(rand_) 
     many_ = int(input('How many people do you want to select: ')) 
     if many_ == 1: 
      print(random.choice(lst_)) 
     elif ppl_ < many_: 
      print('You want to select more people than you have chosen.\n') 
      again() 
     else: 
      THE CODE SHOULD BE HERE * 

       elif i == len(new_list- 1): 
        print(new_list) 
        print('It tried {} time before his decision was made.'.format(total)) 
        break 
       else: 
        total += 1 




    if choose.lower() == 's': 
     randspecial() 
    elif choose.lower() == 'n': 
     randnormal() 
    else: 
     print('Sorry pick again.') 
     print() 

回答

0

random.sample(lst, ppl)會給你從名單lstppl值。

Docs for random.sample

>>> import random 
>>> lst = ['John', 'Paul', 'George', 'Ringo'] 
>>> random.sample(lst, 3) 
['Ringo', 'George', 'Paul'] 
>>> random.sample(lst, 2) 
['Paul', 'George'] 
>>> random.sample(lst, 1) 
['Ringo'] 
+0

是否有可能,它會返回相同名稱的2? –

+0

我測試過了,謝謝你的使用 –