Landry N.
Landry N.

Reputation: 11

How do I select multiple elements from a list?

With this code I'm able to select one comment from comments.txt and comment it without repeating itself. How do I select multiple comments at the same time from the comments.txt without the comments repeating themselves?

def random_comment():
    num = randint(1, COMMAND_AMOUNT)
    while num in USED:
        num = randint(1, COMMAND_AMOUNT)
    USED.append(num)
    return COMMENTS[num]    

USED = []
file = open("comments.txt", "r")
COMMENTS = {num: comment.strip() for num, comment in enumerate(file.readlines(), start=1)}
file.close()

COMMAND_AMOUNT = len(COMMENTS)

Upvotes: 0

Views: 653

Answers (2)

Booboo
Booboo

Reputation: 44128

If you want to ensure there are no repeats:

import random

with open("comments", "r") as f:
    COMMENTS = [comment.strip() for comment in f]
random.shuffle(COMMENTS)

def random_comment():
    return COMMENTS.pop() if COMMENTS else None

# print all the comments until no more:
for comment in iter(random_comment, None):
    print(comment)

Upvotes: 0

zr0gravity7
zr0gravity7

Reputation: 3194

You can use random.sample():

SAMPLE_SIZE = 4 # for example (your question does not indicate how many element should be selected)

def random_comments():
    return random.sample(COMMENTS, SAMPLE_SIZE) 

Upvotes: 1

Related Questions