简体   繁体   中英

Python 3, how to append tuples into list

I just started to learn python. I need to store a csv file data into a list of tuples: tuples to represent the values on each row, list to store all the rows. The function I have problem with is when I need to filter the list. Basically create a copy of the list with only the ones that met criteria. I have successfully appended all the tuples into a list, but when I need to append the tuples into a new list, it doesn't work.

def filterRecord():
    global filtered
    filtered = list()
    try:
        if int(elem[2])>= int(command[-1]): #the condition
                     #if I print(elem) here, all results are correct
        filtered.append(tuple(elem)) #tuples do not add into the list
                                    #len(filtered) is 0
    except ValueError:
        pass


def main():
    infile = open('file.csv')
    L = list()
    for line in infile:
        parseLine() #a function store each row into tuple
    for line in stdin:
        command = line.split() #process user input, multiple lines
        for elem in L:
            if command == 0:
               filterRecord()

If I run it, the program doesn't response. If I force stop it, the traceback is always for line in stdin Also, I am not allowed to use the csv module in this program.

我认为您需要import sysfor line in sys.stdin

You should use python's built-in library to parse csv files (unless this is something like a homework assignment): https://docs.python.org/2/library/csv.html .

You can then do something like:

import csv
with open ('file.csv', 'r') as f:
    reader = csv.DictReader(f, delimiter=",")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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