python - 更改函数以返回整列

标签 python jython

该函数返回单个州和人口,但我需要返回一列中的所有人口,但跳过前 6 行

def findpop(state=None):
    f = open(getMediaPath("population_state_reduced (2).csv"), "rt")
    index = 1
    for line in f:
        if index > 3:
            parts = line.split(',')
            if state is None:
                return [(parts[4], int(parts[5]))]
            else:
                for line in f:
                    if parts[4] == state.capitalize():
                        return int(parts[5])
        index += 1

print findpop()

最佳答案

如果我理解你正确的话,这正是你想要的:

import csv

def findpop(state=None):
    res = []
    with open(getMediaPath("population_state_reduced (2).csv")) as f:
        reader = csv.reader(f)
        for i, line in enumerate(reader):
            if i > 5: # skip first 6 rows
                if state is None:
                    res.append((line[4], int(line[5])))
                else:
                    if line[4] == state.capitalize():
                        return int(line[5])
    return res

关于python - 更改函数以返回整列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40624255/

相关文章:

python - Django 中的两个查询集序列化为 JSON

python - NLTK最大熵分类器原始分数

Jython::嵌入式 PythonInterpreter 是否处理 Python 源代码编码?

python - 将日志记录添加到 jenkins 中的测试结果中

python - Jython 随机模块产生与 cpython 不同的结果

java - 是否有适用于 Jython 或 JRuby 的框架,或者您可以在 JVM 上运行 py 或 ruby​​ 应用程序吗?

python - 在 Python.SocketServer.TCPServer 中有一个很长的 request_queue_size 是危险的吗?

python - 有没有更优雅的方法用 Python 编写这个?

Python 为什么 int ("0") 返回 false

java - 如何在 Jython 项目中创建基于 Sphinx 的文档?