簡體   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