所以我有这个代码将(1,2,3,4)(x4)组成4组,我试图找到一种方法对这些组进行评级。例如。 (1,1,1,1)是一个很好的群体,因为没有其他数字(1,2,3,4)是最差的群体。那么有没有人知道检查组中不同值的数量的方法,例如(1111)有1个值,其中(1,2,3,3)有3个变化。
import numpy
import random
members, n_groups = 4, 4
participants=list(range(1,members+1))*n_groups
#print participants
random.shuffle(participants)
with open('myfile1.txt','w') as tf:
for i in range(n_groups):
group = participants[i*members:(i+1)*members]
for participant in group:
tf.write(str(participant)+' ')
tf.write('\n')
with open('myfile1.txt','r') as tf:
g = [list(map(int, line.split())) for line in tf.readlines()]
print(g)
print(numpy.mean(g, axis=1))
答案 0 :(得分:1)
使用上面的方法创建一个简单的函数:
对于格式(31432123121)的输入数据,您可以使用:
def get_rating(group):
group = str(group) # needed to use set
return len(set(group))
set会将唯一元素的数量排序到集合
>>> set("1111222233")
set(['1', '3', '2'])
>>>
然后len得到了长度。
对于像(1,2,3,1,2)这样的输入数据:
def get_rating(group):
"""
(tuple of ints)->int
"""
group_str = "" # create an empty string to rep the nums
for each_num in group: # iterate through each of the numbers in the group
group_str += str(each_num) # convert each number to a string and append to group_str
return len(set(group_str)) # return a count of the number of different elements in the input group
print get_rating((4,2,3,4,4,4,1,5)) # simple test for function
使用许多列表:
# global var
my_groups = [[3, 1, 3, 1], [2, 2, 4, 2], [3, 4, 3, 2], [4, 4, 1, 1]]
def get_rating(group):
"""
(tuple of ints)->int
"""
group_str = ""
for each_num in group:
group_str += str(each_num)
return len(set(group_str))
# iterates through each list inside the main list.
# Note that lists and tuples can be treated the same except when you want
# to change the internal values
for each_grp in my_groups:
print get_rating(each_grp),
如果要在不同的行上打印它们,请删除最后一行代码中的逗号。