【问题标题】:How to add the same index in multiple lists to a dictionary如何将多个列表中的相同索引添加到字典中
【发布时间】:2021-07-30 00:48:40
【问题描述】:

所以我正在通过 freecodecamp 学习编程,但我被困在教授该课程的教授提供的练习中。这是有问题的练习:

练习 2:编写一个程序,根据提交完成的星期几对每封邮件进行分类。为此,请查找以“From”开头的行,然后查找第三个单词并记录一周中的每一天。在程序结束时打印出字典的内容(顺序无关紧要)。

这是有问题的电子邮件日志http://www.py4e.com/code3/mbox.txt

这是我成功地为这个问题编写自己的代码:

filein = input('Input an email log txt file please: ')
emaillog = open(filein)
days = dict()
for x in emaillog:
    if 'From ' in x:
        print(x.split())
    else:
        continue

我注意到它会打印出大量列表,所有列表都很好地与我关心的区域在所有列表的索引 [2] 处分开。但是,我不明白我应该如何处理数据以推断日期并构建我的字典。

编辑:感谢你们的帮助,这就是我最终想出的结果,它给了我正确的结果:

  filein = input('Input an email log txt file please: ')
emaillog = open(filein)
days = dict()
lis = list()
for x in emaillog:
    if 'From ' in x:
        array = x.split()
        day = array[2]
        days[day] = days.get(day, 0)+1
    else:
        continue
print(days)

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:

    以下是您如何利用您创建的算法的想法来完成此任务

    filein = input('Input an email log txt file please: ')
    emaillog = open(filein)
    days = dict()
    
    for x in emaillog:
        if 'From ' in x[:5]:
            L = x.split()
            if L[2] in days:
                days[L[2]] +=1
            else: 
                days[L[2]] =0   
    
    

    输出:

    {'Sat': 60, 'Fri': 314, 'Thu': 391, 'Wed': 291, 'Tue': 371, 'Mon': 298, 'Sun': 65}
    

    但是你可以在这里使用 RegEx。

    【讨论】:

      【解决方案2】:

      我不会为你做整个练习,但以下应该会给你一个跑步的开始:

      filein = input('Input an email log txt file please: ')
      
      days = dict()
      with open(filein) as emaillog:
          for line in emaillog:
              if line.startswith('From'):
                  print(line, end='')
                  row = line.split()  # Convert line into list of words.
                  # Get day from list and add 1 to its counter in the days dict.
                  ...
      
      print(days)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-23
        • 2019-12-27
        • 2021-04-26
        • 1970-01-01
        • 1970-01-01
        • 2013-09-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多