打印与'dict'中的信息相关的元素

时间:2015-05-24 03:14:58

标签: python list python-2.7 dictionary

在理解“inputYear = input('Please enter the year: ') inFile = open('babyQldAll.csv', 'rU') cvsFile = csv.reader(inFile, delimiter=',') dict = {} for row in cvsFile: year, name, count, gender = row if (year == inputYear) and (gender == 'Boy'): dict[name] = count print('Popular boy names in year %s are:' % inputYear) # According to information in 'dict', print (name, count) sorted by 'name' in alphabetical order print("Print boy names... ") inFile.close() ”命令时遇到一些麻烦,如果有人可以帮助我,我将非常感激。

这是我到目前为止的代码:(我已经放入了我需要帮助的地方和内容)     import csv

Popular boy names in year "2010" are: Aidan 119, Alex 224, Derek 143, Steven 212, Tom 111.....

使用上面的代码我试图获得结果:

File 2010:
2010, Steven, 212, Boy
2010, Mary, 423, Girl
2010 , Tom, 111, Boy
2010, Jessica, 223, Girl
(and so on)

来自以下输入:

  void refreshtable()  
    {
        var query = (from x in de.HeaderTrainingAllocations
                     join y in de.MsTrainings on x.TrainingID equals y.TrainingID
                     join z in de.MsUsers on x.UserID equals z.UserID
                  select new
                     {
                         x.AllocationID,
                         x.TrainingID,
                         z.UserName,
                         x.TrainingStartDate,
                         TrainingEndDate = System.Data.Objects.EntityFunctions.AddDays(x.TrainingStartDate, ((y.TrainingDuration - 1) * 7)),
                         y.TrainingDuration,
                         x.Capacity
                     }
                     );//get all data from tables
        dataGridView1.DataSource = query;




          for (int i = 0; i < dataGridView1.RowCount; i++)
          {
              int currentcapacity;
              Int32.TryParse(dataGridView1.Rows[i].Cells[6].Value.ToString(),out currentcapacity);

              String idA = dataGridView1.Rows[i].Cells[0].Value.ToString(); //read allocation ID on cell 0
              var cek = (from x in de.DetailTrainingAllocations

                         where x.AllocationID==idA
                         select x).Count(); //to get amount of data in table detailTransaction

              dataGridView1.Rows[i].Cells[6].Value =currentcapacity- cek;//this code won't change the value of the rows in datagridview
          }
    }

2 个答案:

答案 0 :(得分:2)

这应该做:

from __future__ import print_function

import csv
import sys

if sys.version_info.major < 3:
    input = raw_input

input_gender = 'Boy'  # could make this a user-supplied value too

input_year = input('Please enter the year: ').strip()
file_name = 'babyQldAll.csv'

with open(file_name) as fobj:
    csv_file = csv.reader(fobj)
    name_counts = {}
    for row in csv_file:
        year, name, count, gender = (entry.strip() for entry in row)
        if year == input_year and gender == input_gender:
            name_counts[name] = int(count)

print('Popular {} names in year {} are:'.format(input_gender.lower(), input_year))
for name, count in name_counts.items():
    print(name, count)

print('\nBoys names in alphabetical order:')
for name in sorted(name_counts.keys()):
    print(name)

print('\nBoys names in alphabetical order and counts:')
for name, count in sorted(name_counts.items()):
    print('{}: {}'.format(name, count))

一些注意事项:

  1. 在Python 2中,您应该使用raw_input,其中会变成input Python 3.一种方法是让你的程序在Python 2中以相同的方式工作 并且3会将其添加到文件的开头:

    import sys
    
    if sys.version_info.major < 3:
        input = raw_input
    

    现在无论Python版本是什么,都可以使用input

  2. 您的输入在逗号后面有空格。仅限csv阅读器 查找逗号,空格是列表中字符串的一部分 一排。用(entry.strip() for entry in row)解决它剥离它 此

  3. 所以我比较一年的字符串。我可能值得转换 同时,input_yearyearint并对其进行比较。

  4. 使用问题中的示例文件运行程序看起来像thi:

    Please enter the year: 2010
    Popular boy names in year 2010 are:
    Tom 111
    Steven 212
    
    Boys names in alphabetical order:
    Steven
    Tom
    
    Boys names in alphabetical order and counts:
    Steven: 212
    Tom: 111
    

答案 1 :(得分:1)

dict[]用于使用密钥检索存储在字典中的值。因此,如果您将上述内容存储为:

names = {'Steven': [212, 'Boy', 2010], 'Mary': [423, 'Girl', 2010]}

想要检索史蒂文的信息,你会说names['Steven'],它会返回列表[212, 'Boy', 2010]

我不认为这会完全回答你的问题,但它应该可以帮助你开始。如果您想对字典进行预先排序,您可能还需要查看this