简体   繁体   English

无法从Python函数返回列表元素

[英]Cannot return list elements from Python function

I have a function, table() , that reads a csv file and returns the rows in individual lists. 我有一个函数table() ,它读取csv文件并返回单个列表中的行。 I want to map these lists to create a dictionary, with field headers being the keys and the underlying rows being the values. 我想映射这些列表来创建一个字典,字段标题是键,底层行是值。 I cannot seem to do this however. 但是我似乎无法做到这一点。 When I try to call only the first element within the list of lists I created from the function ( l ) in the command prompt, it returns all the lists up to 'N', the first letter in the word 'None', despite me breaking (return) if reader is None. 当我尝试仅调用我在命令提示符中从函数( l )创建的列表列表中的第一个元素时,它返回所有列表,直到'N',即'None'中的第一个字母,尽管我如果读者是无,则打破(返回)。 When I do the same with a sys.stdout to a text file, it does the same, but the 'N' is replaced with <type 'list'> . 当我使用sys.stdout对文本文件执行相同操作时,它会执行相同操作,但“N”将替换为<type 'list'> Does anyone know what I'm doing wrong, and how I can go about creating a dictionary (or a list of columns, for that matter) from a CSV file given my table() function? 有谁知道我做错了什么,以及我如何在给出table()函数的情况下从CSV文件创建字典(或列表列表table()

import csv

def table():
    with open('C:\\Python27\\test.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            print row
        if reader is None:
            return

l = list(str(table()))
keys = l[0]
print keys

Output text file: 输出文本文件:

['Field1', 'Field2', 'Field3', 'Field4']
['a', '1', 'I', 'access']
['b', '2', 'II', 'accessing\n']
['c', '3', 'III', 'accommodation']
['d', '4', 'IIII', 'basically']
<type 'list'>

More pythonically 更诡异

def table():
    with open('C:\\Python27\\test.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            yield row

You don't actually return anything from the table function. 您实际上没有从table函数返回任何内容。 Try it like this: 试试这样:

def table():
    with open('C:\\Python27\\test.csv', 'rb') as f:
        lines = []
        reader = csv.reader(f)
        if reader:
            for row in reader:
                lines.append(row)
            return lines
        else:
            return []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM