Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何分配参与者参与研究?_Python_List_Random_Numbers - Fatal编程技术网

Python 如何分配参与者参与研究?

Python 如何分配参与者参与研究?,python,list,random,numbers,Python,List,Random,Numbers,我希望能够要求用户输入样本量中的参与者数量,并输入参与者的最大和最小年龄。接下来,我希望代码随机分配给每个参与者:性别(1为男性,2为女性)和参与者的年龄。然后,该程序应分别显示男性和女性参与者的总数以及他们的平均年龄 我是Python的新手,所以我一直在网上搜索如何为研究中的每个数字分配性别(1或2)。我可以将样本大小拆分为一个列表,但我不知道如何将所述值分配给每个数字,也许我只是缺少一个简单的函数 num = int(input('Enter the number of participan

我希望能够要求用户输入样本量中的参与者数量,并输入参与者的最大和最小年龄。接下来,我希望代码随机分配给每个参与者:性别(1为男性,2为女性)和参与者的年龄。然后,该程序应分别显示男性和女性参与者的总数以及他们的平均年龄

我是Python的新手,所以我一直在网上搜索如何为研究中的每个数字分配性别(1或2)。我可以将样本大小拆分为一个列表,但我不知道如何将所述值分配给每个数字,也许我只是缺少一个简单的函数

num = int(input('Enter the number of participants in the study: '))
max = int(input('Enter the maximum age of the participants: '))
min = int(input('Enter the minimum age of the participants: '))

x = list(range(num+1))

对于此策略,您可以使用以下代码来实现输出。谢谢

from random import randint

num = int(input('Enter the number of participants in the study: '))
max = int(input('Enter the maximum age of the participants: '))
min = int(input('Enter the minimum age of the participants: '))
male = 0
female = 0
i = 0
li= list()
while i < num:
    age = randint(min, max)
    gender = ('male') if randint(1, 2) == 1 else 'female'
    li.append({gender:age})
    i= i+1

for i in li:
    if i.has_key('male'):
        male = male + 1
    else:
        female = female + 1
print(li)
print(male)
print(female)
来自随机导入randint
num=int(输入('输入参与研究的人数:'))
max=int(输入('输入参与者的最大年龄:'))
min=int(输入('输入参与者的最低年龄:'))
男性=0
女性=0
i=0
li=列表()
而我
首先创建一个emply
列表
,然后循环
参与者次数,每次迭代
追加()
一个包含随机分配的年龄和性别值的元组。您可以使用该函数生成随机整数值。我遇到的唯一问题是,sample_dict中的参与者数量与输入的参与者数量不匹配。它只产生了大约一半的参与者,他们要么接受要么接受。有没有关于如何修复的想法?只是更新了代码。它应该很好用。谢谢你,非常感谢!有一点需要指出,我认为has_key在最新版本的python中不起作用。取而代之的是“如果i中的‘男性’:”很好用:)