Python return list from function

后端 未结 8 943
面向向阳花
面向向阳花 2020-12-13 08:27

I have a function that parses a file into a list. I\'m trying to return that list so I can use it in other functions.

def splitNet():
    network = []
    f         


        
8条回答
  •  萌比男神i
    2020-12-13 09:18

    The names of variables in a function are not visible outside, so you need to call your function like this:

    networks = splitNet()
    print(networks)
    

    A couple of other notes:

    • You may want to convert your function to an iterator, using yield.
    • You don't need to call readlines; the function itself is an iterator.
    • Your function may be leaking the file handle. Use the with statement.
    • You can use str.split, which is more readable and easier to understand than string.split.
    • Your file looks to be a CSV file. Use the csv module.

    In summary, this is how your code should look like:

    import csv
    def splitNet():
        with open("/home/tom/Dropbox/CN/Python/CW2/network.txt") as nf:
            for line in csv.reader(nf, delimiter=','):
                yield map(int, line)
    network = list(splitNet())
    print (network)
    

提交回复
热议问题