Python 计算某个位置在列表中显示的次数

Python 计算某个位置在列表中显示的次数,python,python-3.x,list,Python,Python 3.x,List,所以我有一个“客户机”列表,我需要计算这个“元素”在每行中出现的次数。.zip中的文本文件的一小部分: 例如,如果我想知道这个列表中有多少女性 到目前为止,我已经尝试: def getColumnDistribution(filename,columnNum): file = open(filename,"r") listoflists = [] for line in file: stripped_line = line.strip()

所以我有一个“客户机”列表,我需要计算这个“元素”在每行中出现的次数。.zip中的文本文件的一小部分:

例如,如果我想知道这个列表中有多少女性

到目前为止,我已经尝试:

def getColumnDistribution(filename,columnNum):

    file = open(filename,"r")
    listoflists = []

    for line in file:

        stripped_line = line.strip()

        line_list = stripped_line.split()

        listoflists.append(line_list)

        NUMBER = line_list.count(line_list[columnNum])
它不断出现“列表索引超出范围”
有人知道我如何修复它或使用更好的方法吗?

Python为您提供了许多工具,使这些任务变得轻松。例如,您可以将csv解析问题传递给模块,并将其计数器传递给。然后就是几行:

import csv
from collections import Counter

with open(path, 'r') as f:
    reader = csv.reader(f)
    headers = next(reader)    # pop off the header row

    genderCounts = Counter(row[1] for row in reader)

print(genderCounts['female'])
# 15167

print(genderCounts['male'])
# 14833
如果使用from csv,则可以按列名称索引,这使代码更具可读性:

with open(path, 'r') as f:
    reader = csv.DictReader(f)

    genderCounts = Counter(row['Gender'] for row in reader)
当然,如果你在这样的数据上做了大量工作,熊猫会让你的生活变得更加轻松:

import pandas as pd

df = pd.read_csv(path)
df['Gender'].value_counts()

# female    15167
# male      14833
# Name: Gender, dtype: int64

这对你有用。在3.6v电压下测试

import csv

def openFile(file_name:str)->tuple:
    with open(file_name,'r') as csv_file:
        csv_reader = csv.reader(csv_file)
        return tuple(csv_reader)  

def getColumnDistribution(csv_data:tuple,name_to_count:str)->int:

    num_of_count = [idx for idx,rows in enumerate(csv_data) if name_to_count in rows]
    print("number of occurence:",num_of_count)
    return len(num_of_count)

#driver code
csv_data = openFile(your_csv_file_name)
getColumnDistribution(csv_data,'female')

python代码缩进搞砸了。请首先修复您的文件是CSV,您应该将其视为CSV。看一看这张照片。请注意,您在当前代码中使用空格分隔,而应该使用逗号分隔。但如前所述,使用适合您的模块。我建议使用csv模块和列表理解来解决您的问题。请提供csv文件。它是一个.txt文件而不是csvIt文件,无论您添加了什么扩展名。它是用逗号分隔的,您会得到错误,因为您是用空格分隔的,而不是用逗号分隔的。
import csv

def openFile(file_name:str)->tuple:
    with open(file_name,'r') as csv_file:
        csv_reader = csv.reader(csv_file)
        return tuple(csv_reader)  

def getColumnDistribution(csv_data:tuple,name_to_count:str)->int:

    num_of_count = [idx for idx,rows in enumerate(csv_data) if name_to_count in rows]
    print("number of occurence:",num_of_count)
    return len(num_of_count)

#driver code
csv_data = openFile(your_csv_file_name)
getColumnDistribution(csv_data,'female')