如何替换附加但随机模块的双列表项?

时间:2017-09-22 23:02:52

标签: python list random module

我有一些代码可以让用户在列表中附加单词。并且假设用户附加了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()

1 个答案:

答案 0 :(得分:0)

random.sample(lst, ppl)会从列表ppl中为您提供lst个值。

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']