python - 处理文件读取的函数
问题描述
我有一个必须阅读的文件。在每一行中,都有姓名、年龄、身高和体重。文件中有很多行,我只需要名称。这是我的代码:
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()
我需要一个函数来询问列表中一组(一些数字)的大小,并从该列表中给出随机名称。
我不知道如何实现该功能。我有点了解函数的逻辑,但我不知道应该将函数放在代码中的哪个位置(比如哪一行)。
解决方案
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)
推荐阅读
- c - 函数连接额外的字符
- angularjs - 如何使用angularjs从其他js文件中注入模块中的依赖项
- c# - C#控制台:设置windows键盘RepeatDelay
- twilio - 任务关闭后,Twilio 工作人员活动不会从忙碌变为空闲
- keycloak - 是否可以使用自定义用户属性进行 KeyCloak 身份验证?
- memory-leaks - 重复添加/删除导致内存泄漏
- sql - max 函数在有 case when 子句时没有
- html - 如何通过select添加请求参数?
- java - 传递对 javafx.application.Application 的引用
- android - 在自定义工具栏中对齐多个视图