[英]Finding average per integer compared to each element in a given list
所以我正在练习对 3 人的调查进行 21 个问题的数据处理。我需要给出每个 # 给出的平均答案。我不确定如何分离数字并进行比较,同时将字母排除在外。
name=["AAAAA 4 2 1 2 4 2 4 4 5 2 2 1 5 2 4 3 1 1 3 3 5",
"BBB 5 2 1 2 4 5 4 4 1 2 2 2 4 4 4 3 1 2 3 3 2",
"K 4 1 2 1 2 1 2 5 1 1 1 1 4 2 2 1 5 1 3 4 1"]
例如。 1=4.33
我的尝试:
def most_frequent(name):
counter = 0
num = name[0]
for i in range (len(name)):
curr_frequency = name[0].count(str(i))
if(curr_frequency> counter):
counter = curr_frequency
num = i
return num
你可以试试这个:
name=["AAAAA 4 2 1 2 4 2 4 4 5 2 2 1 5 2 4 3 1 1 3 3 5",
"BBB 5 2 1 2 4 5 4 4 1 2 2 2 4 4 4 3 1 2 3 3 2",
"K 4 1 2 1 2 1 2 5 1 1 1 1 4 2 2 1 5 1 3 4 1"]
for line in name :
parts = line.split() # using space as a separator
word = parts[0] # extract the word
numbers = map( float, parts[1:] ) # convert the numbers
print( word, numbers )
# now you may calculate whatever you want =)
如果您想打印每个 # 数字的平均值,您可以尝试这样做,而不必每次在循环中拆分行。
name = ["AAAAA 4 2 1 2 4 2 4 4 5 2 2 1 5 2 4 3 1 1 3 3 5",
"BBB 5 2 1 2 4 5 4 4 1 2 2 2 4 4 4 3 1 2 3 3 2",
"K 4 1 2 1 2 1 2 5 1 1 1 1 4 2 2 1 5 1 3 4 1"]
name = [name[i].split(" ") for i in range(len(name))]
for i in range(1, len(name[0])):
print((int(name[0][i])+int(name[1][i])+int(name[2][i]))/3, sep = " ")
尝试这个:
name=["AAAAA 4 2 1 2 4 2 4 4 5 2 2 1 5 2 4 3 1 1 3 3 5",
"BBB 5 2 1 2 4 5 4 4 1 2 2 2 4 4 4 3 1 2 3 3 2",
"K 4 1 2 1 2 1 2 5 1 1 1 1 4 2 2 1 5 1 3 4 1"]
Average = Counter()
length = 0
for item in name:
thelist = item.split(' ')[1:]
length += len(thelist)
Average += Counter(thelist)
print(Average)
print([(i, Average[i] / length * 100.0) for i in Average])
输出:
Counter({'2': 18, '1': 17, '4': 14, '5': 7, '3': 7})
[('4', 22.22222222222222), ('2', 28.57142857142857), ('1', 26.984126984126984), ('5', 11.11111111111111), ('3', 11.11111111111111)]
您可以创建一个简单的 for 循环来从列表中删除空格和字母。
您可以在列表上使用sum()
函数来获取该完整列表的总和,然后除以列表的len()
以获得平均值。
这应该工作:
name=["AAAAA 4 2 1 2 4 2 4 4 5 2 2 1 5 2 4 3 1 1 3 3 5", "BBB 5 2 1 2 4 5 4 4 1 2 2 2 4 4 4 3 1 2 3 3 2", "K 4 1 2 1 2 1 2 5 1 1 1 1 4 2 2 1 5 1 3 4 1"]
for i in range(0, len(name)) :
tempOut = []
temp = list(name[i])
for j in range(0, len(temp)) : #65 - 123
if ord(temp[j]) not in range(65, 122) :
tempOut.append(temp[j])
name[i] = ''.join(tempOut)
sums = []
for i in range(0, len(name)) :
sumTemp = []
temp = list(name[i].replace(' ', ''))
for j in range(0, len(temp)) :
sumTemp.append(int(temp[j]))
tempSums = sum(sumTemp)/len(temp)
sums.append(tempSums)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.