【问题标题】:Function that handles a file reading处理文件读取的函数
【发布时间】:2019-11-22 19:05:33
【问题描述】:

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

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()

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

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

【问题讨论】:

    标签: python function file


    【解决方案1】:

    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)
    

    【讨论】:

    • 这并不能真正回答我的问题
    • 你的意思是,你从哪里得到传递 to generateGroup 的值(顺便说一句,它不能按预期工作,因为它只会打印一个随机名字)?
    • 我的意思是,例如:现在它只打印回名称列表,但 def generateGroup(sizeOfGroup) 函数根本不起作用,就像它不打印任何东西一样。它应该采用我从读取该文件中创建的 lst 并且该函数应该要求一些数字,比如说 4 并从该 lst 打印出 4 个随机名称。
    • 你在打电话 generateGroup吗?你展示的只是定义它。
    猜你喜欢
    • 2022-01-07
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多