【问题标题】:Get data of another function获取另一个函数的数据
【发布时间】:2020-05-28 03:21:48
【问题描述】:

大家好,需要一些帮助,我已经阅读了一个使用开放语法的 csv 文件,我想将此数据用于另一个函数。复制函数数据的最佳方法是什么。

这是我的代码:

import csv

def read_csv_file(filename):
    temperatures = []
    fans = []
    modes = []
    louvers = []
    swings = []
    with open(filename, 'r') as csv_file:
        csv_reader = csv.reader(csv_file)

        for line in csv_reader:
            temperatures.append(line[1])
            fans.append(line[2])
            modes.append(line[3])
            louvers.append(line[4])
            swings.append(line[5])
        return temperatures
        return fans
        return modes
        return louvers
        return swings

def get_feature():

    result = {}
    result['feature'] = [{'feature_name': '', 'ftype': 'section_option', 'group_name': '', 'value': ''}]
    result1 = dict()
    result1 = {'definition':[]}
    read_csv_file(filename)

    print (temperatures)


filename = 'ir_raw.csv'
csv_data = read_csv_file(filename)

我想在 def get_feature(): 函数中打印我的 csv 文件数据。提前致谢!!

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    您只能从函数返回一次,因此在 read_csv_file 中只执行第一个返回语句(返回温度)。其余数据被遗忘。

    解决此问题的一种简单方法是将所有列表放入一个元组中,然后返回该元组。所以在 read_csv_file 中,你会输入:

    data = (temperatures, fans, modes, louvers, swings)
    return data
    

    然后要在以后使用这些数据,您需要将该数据保存到一个变量中,并为要打印的任何列表编制索引。

    使用您的方法的完整解决方案可能是:

    import csv
    
    def read_csv_file(filename):
        temperatures = []
        fans = []
        modes = []
        louvers = []
        swings = []
        with open(filename, 'r') as csv_file:
            csv_reader = csv.reader(csv_file)
            for line in csv_reader:
                temperatures.append(line[1])
                fans.append(line[2])
                modes.append(line[3])
                louvers.append(line[4])
                swings.append(line[5])
            return (temperatures, fans, modes, louvers, swings)
    
    def get_feature(data):
        #... do whatever you plan on doing
        print(data[0]) # for temperatures
        print(data[1]) # for fans
        print(data[2]) # for modes
        print(data[3]) # for louvers
        print(data[4]) # for swings
    
    filename = 'ir_raw.csv'
    csv_data = read_csv_file(filename)
    get_feature(csv_data)
    

    或者,可以使用 numpy.genfromtxt 或 pandas.read_csv,而不是使用 CSV 模块。

    【讨论】:

    • 进展顺利。感谢您的大力帮助!
    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 2021-03-22
    • 2021-07-12
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多