2017-09-22 38 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

我测试过了,谢谢你的使用 –