python - 显示基于元组的排序列表并在字典中循环

标签 python list loops sorting tuples

我正在做 Coursera python 练习,这是问题

Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.>

From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008

Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.

包含文本文件的链接是:http://www.py4inf.com/code/mbox-short.txt

期望的输出如下:

04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1

这是我的代码:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
count = dict()
lst = list()

for line in handle:
    if line.startswith('From '):
        word = line.split()
        temp = word[5]
        time= temp.split(':')
        hour = time[0]
        count[hour] = count.get(hour, 0) + 1
    
for k, v in count.items():
    lst.append((k, v))

print lst.sort()

但是,我得到的结果是“无”。当我将最后一行更改为:

print lst

结果变成:

[('11', 6), ('10', 3), ('15', 2), ('14', 1), ('04', 3), ('16', 4), ('19', 1), ('18', 1), ('09', 2), ('17', 2), ('06', 1), ('07', 1)]

我用谷歌搜索并找到了这个问题的一个解决方案,如下所示:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()

for line in handle:
    wds = line.split()
    if len(wds) < 5 : continue
    if wds[0] != "From" : continue
    when = wds[5]
    tics = when.split(":")
    if len(tics) != 3 : continue
    hour = tics[0]
    counts[hour] = counts.get(hour,0) + 1
lst = counts.items()
lst.sort()
for key, val in lst :
    print key, val

除了文本文件中的循环迭代行之外,我没有看到我的错误代码和我从 github 获得的正确代码之间的功能差异。

有人可以给我一些见解吗?

最佳答案

取自documentation ,调用 lst.sort() 将对列表进行就地排序。这意味着它直接修改列表。您要使用的是 sorted(lst) ,这将返回一个排序列表。

或者,正如评论中指出的那样,调用

lst.sort()
print(lst)

获得您想要的输出。

关于python - 显示基于元组的排序列表并在字典中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001931/

相关文章:

python - 如何与列表匹配并打印列表中的行

python - Pandas:如何有条件地对两个不同数据框中的值求和

python - 将 pandas 列 'day of year' 转换为日期时间 (%m-%d)?

html - 我怎样才能使用列表制作下拉菜单

php - 在 WooCommerce 循环中的子类别和产品之间添加分隔线

loops - 在React中使用for循环和switch case来动态渲染不同的组件

c - printf 打印额外的 * 字符

python - 根据列值拆分数据框

python - 什么是从 python 字符串中删除空行的快速单行代码?

python - 从数组中删除列表符号