凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

python 随机抽取列表中的几条

2020-04-15 python 1294
import random

with open("./data/400.txt", "r", encoding="utf-8") as f:
    keywords = f.read().split("\n")

def get_keywords(keywords, qu_num):
    if qu_num is None:
        qu_num = 10
    total = len(keywords)
    rand_len = total - 1
    lst = []
    result_keywords = []
    index = 0
    all_index = 0
    while True:
        key = random.randint(0, rand_len)
        if key not in lst:
            index += 1
            if index > qu_num:
                break

            lst.append(key)
            # 添加进keywords
            result_keywords.append(keywords[key])
            
        all_index += 1
        if all_index > total:
            break
    return result_keywords


words = get_keywords(keywords, 3)
print(words)


文章评论

0条评论