【问题标题】:Python 3, how to append tuples into listPython 3,如何将元组附加到列表中
【发布时间】:2017-11-19 19:04:33
【问题描述】:

我刚开始学习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 模块。

【问题讨论】:

  • 过滤条件是什么?
  • @WillemVanOnsem 当 elem[2] 大于或等于用户输入的数字时

标签: python list csv append tuples


【解决方案1】:

我认为你需要import sys 并使用for line in sys.stdin

【讨论】:

  • 我确实导入了系统
  • 你是不是用sys.stdin 而不是stdin?否则,您能否发布完整的错误消息?
  • 我做了from sys import stdin。我没有收到任何错误消息,程序一直运行,直到我强制关闭它
  • 我不确定有什么东西会强制阻止程序接受输入,除非你强制它。您是否尝试过使用 Ctrl + Z 或 Ctrl + D 取消输入?这应该仍然继续程序
  • 我在 Mac 上使用 Ctrl+C,这给了我键盘中断。我刚试过你的建议,但还是一样。
【解决方案2】:

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

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

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

【讨论】:

  • "另外,我不允许在这个程序中使用 csv 模块。"
猜你喜欢
  • 1970-01-01
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 2017-12-18
  • 2019-02-26
  • 2019-06-23
相关资源
最近更新 更多