计算给定lis中每个元素的平均值

2024-04-20 13:02:59 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我正在练习一项针对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

Tags: 答案namemostfordef字母counter数字
3条回答

可以创建一个简单的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)

试试这个:


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

你可以试试这个:

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

相关问题 更多 >