【问题标题】:storing for loop iteration data存储for循环迭代数据
【发布时间】:2012-05-27 17:07:45
【问题描述】:

我在玩cgi(上传文件形式),

我将文件作为存储对象接收,并将其存储在(输入)变量中。

这是简单的迭代。

for file in input:
  filepath = ....
  filename, fileext = os.path.splitext(filepath)
  file_real_name = ....
  file_size = ....
  file_type = ...
  file_url = ....
  file_short_name = ...
  file_show_link = ....

  # etc

如果只有一个文件会很容易,但如果我有多个文件呢?

我怎样才能拥有另一个保存所有迭代信息的值

uploaded_files 这样我可以访问每个上传的文件以及上述迭代的所有信息?

我尝试阅读文档,但我还无法理解一些迭代概念,抱歉 :)

【问题讨论】:

  • @Alex 谢谢,举个例子就好了。

标签: python storage iteration


【解决方案1】:

您想使用数据结构来保存数据。根据复杂程度,您可能只想使用字典列表:

files = []
for file in input:
    files.append({
        "path": get_path(file),
        "name": get_name(file),
        "size": get_size(file),
        ...
    })

或者,如果您发现需要对数据执行大量操作,您可能想要创建自己的类并创建对象列表:

class SomeFile:
    def __init__(self, path, name, size, ...):
        self.path = path
        ...

    def do_something_with_file(self):
        ...

files = []
for file in input:
    files.append(SomeFile(get_path(file), get_name(file), get_size(file), ...))

请注意,您在此处遵循通过迭代迭代器来构建列表的模式。您可以使用list comprehension 有效地做到这一点,例如:

[{"path": get_path(file), "name": get_name(file), ...} for file in input]

还要注意fileinput 是非常糟糕的变量名,因为它们会掩盖内置函数file()input()

【讨论】:

  • 谢谢,get_path() 是我必须定义的方法吗?
  • @static 这只是占位符代码 - 您可以在其中放置任何您想要的代码来生成您需要的值。
  • 太好了,非常感谢您的详细回答。
【解决方案2】:
results = []
for i in range(5):
    file_data = {}
    file_data['a'] = i
    file_data['b'] = i**2
    results.append(file_data)
print results

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
相关资源
最近更新 更多