首页 > 解决方案 > 处理文件读取的函数

问题描述

我有一个必须阅读的文件。在每一行中,都有姓名、年龄、身高和体重。文件中有很多行,我只需要名称。这是我的代码:

import random
import string

dictionary = {}
lst = []

with open("persons.dat","r") as file:
    for line in file:
        items = line.split(',') #this makes this ['Bill Johnson', '31', '196', '93']
        key = items[0]
        dictionary[key] = []
        for i in range(1,len(items)):
            dictionary[key].append(int(items[i]))
    #print(dictionary)

    for key in dictionary.keys():
        lst.append(key)
    print(lst)


def generateGroup(sizeOfGroup):
    for names in range(sizeOfGroup):
       random_names = random.choice(lst)
    print(random_names)

我的代码按预期获取列表中的所有名称。该代码可以正常工作generateGroup()

我需要一个函数来询问列表中一组(一些数字)的大小,并从该列表中给出随机名称。

我不知道如何实现该功能。我有点了解函数的逻辑,但我不知道应该将函数放在代码中的哪个位置(比如哪一行)。

标签: pythonfunctionfile

解决方案


random.sample正是这样做的。

def generateGroup(sizeOfGroup):
    print(random.sample(lst, k=sizeOfGroup))

random.sample返回一个列表。您可以自己累积列表

random_names = []
for names in range(sizeOfGroup):
     random_names.append(random.choice(lst))
print(random_names)

random.sample确保您不会选择两次相同的名称。

一旦generateGroup正确定义,您仍然需要使用参数调用它:

while True:
    try:
        n = int(input("Enter a number: "))
        break
    except ValueError:
        print("That's not an integer, try again")

generateGroup(n)

推荐阅读