如何:在Python中创建一个大的,可读的目录?

时间:2015-04-10 14:36:28

标签: python file-handling

我被分配了一项任务,我正在努力探索如何解决这个问题(我在Python上没有太多经验,而且我无法想出办法来实现它工作)。

基本上,我已经创建了一个测验,用户输入他们的姓名和小组,然后在给出分数之前回答问题。

现在我需要添加代码以允许它执行此操作:

  • 取决于他们输入的组,将信息写入某个CSV文件
  • 将用户的姓名和得分写入文件

这似乎很直接,但我不知道该怎么做。完成此操作后,扩展名是最新的三个分数(而不仅仅是一个)应存储在每个用户的文件中。

此外,我需要创建一个辅助程序来读取文件中的信息。在此程序中,用户需要能够以三种不同的方式阅读信息:

  • 按用户的字母顺序排列'名字,只显示他们的最高分
  • 显示用户'最高分,从最高到最低(以他们的名字命名)
  • 显示用户'平均分数,从最高到最低(以他们的名字命名)

正如您所看到的,这是一个非常壮举!任何关于如何去做的建议(一般方法,有用代码的片段等)都非常感谢。

谢谢!

1 个答案:

答案 0 :(得分:1)

以下是您提出的一些摘录。

获取用户输入

user_input = raw_input("Prompt here: ")  # Python 2.x
user_input = input("Prompt here: ")      # Python 3.x
# user_input will be a string

从文本文件中读取

with open(filename, 'r') as f:
    for line in f:
        print(line)

写入文本文件

#lines = <some list of lines you've built>

with open(filename, 'w') as f:
    for line in lines:
        f.write(line)  # line should be terminated with newlines (\n)

从csv文件中读取(使用csv模块)

with open(csvfile, 'rb') as f:
    reader = csv.reader(f)
    for line in reader:
        print(line)

写入csv文件(使用csv模块)

#rows = <some list of rows you've built, rows should be iterable>

with open(csvfile, 'wb') as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)

(如果你正在使用dicts,DictWriter类可能会引起关注。)

使用defaultdict构建值为列表的字典

from collections import defaultdict

d = defaultdict(list)

# list is some list of lists
for row in list:
    key = row[0]  # These are examples
    val = row[2]  # ''
    d[key].append(val)

# d is now a dictionary, where the values are lists

从字典中获取键/值/项

#d = <some dictionary>
for k in d:             # Iterate over dictionary keys
    print(k)

for v in d.values():    # Iterate over values
    print(v)

for k,v in d.items():   # Iterate over key,value pairs
    print(k)  # key
    print(v)  # value

(在Python 2中,更有效的方法是使用itervalues()iteritems(),但我们只是保持简单。)

排序列表

x = [2,4,6,1,3,5]
y = [1,3,5,2,4,6]

x.sort()       # In-place sorting, doesn't return anything
print(x)       # [1, 2, 3, 4, 5, 6]

z = sorted(y)  # Create a new, sorted list
print(y)       # [1, 3, 5, 2, 4, 6]  (still unsorted)
print(z)       # [1, 2, 3, 4, 5, 6]

sort()sorted()都接受reverse参数,当为True时,将以相反的顺序对其进行排序(通常这会使其从最高到最低)。

例如:

x.sort(reverse=True)    # or,
sorted(x, reverse=True)

寻找最高分

scores = [84.5, 90, 80, 82, 99]
high   = max(scores)
print(high)  # 99