繁体   English   中英

Python 3,如何将元组追加到列表中

[英]Python 3, how to append tuples into list

我刚刚开始学习python。 我需要将一个csv文件数据存储到一个元组列表中:元组表示每一行的值,列表存储所有行。 我有问题的功能是何时需要过滤列表。 基本上仅使用满足条件的列表创建列表的副本。 我已经成功地将所有元组追加到列表中,但是当我需要将元组追加到新列表中时,它不起作用。

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()

如果我运行它,该程序将不会响应。 如果我强制停止它,则追溯始终for line in stdin此外,不允许在此程序中使用csv模块。

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

您应该使用python的内置库来解析csv文件(除非这类似于家庭作业): https : //docs.python.org/2/library/csv.html

然后,您可以执行以下操作:

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

暂无
暂无

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

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