小于且结束条件为的计数值

2024-10-08 19:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

问题: 在.txt文件中找到以“1001”结尾的单位代码,如果有人得到低于50分的分数,则计算此单位。如果是,则计算。如果否,则值为0

我的代码:

skipped_header = True
counters_unit_code = {}
with open("inp.txt") as csv_file:
  for line in csv_file:
    if skipped_header:
      skipped_header = False
      continue
    record = line.rstrip().split(':')
    unit_code = record[2].endswith('1001')
    min_mark = int(record[4])
    if unit_code not in counters_unit_code:
      counters_unit_code[unit_code]=0
    if min_mark < 50:
      counters_unit_code[unit_code] += 1

for unit_code in counters_unit_code:
  print(str(unit_code),counters_unit_code[unit_code])

我的输出:

False 1
True 3

预期产量:

engl1001 3
math1001 0

txt文件(inp.txt):

Name:unikey:unitcode:year:mark
Joe Smith:jsmi3031:chem1101:2016:40
Oleg Catem:ocat3031:chem1101:2016:79
Joe Smith:jsmi3031:engl1001:2015:0
Joe Smith:jsmi3031:engl1001:2016:45
Tim Gold:tgol2145:engl1001:2016:46
Paula Dong:pdon1234:engl1001:2016:91
Joe Smith:jsmi3031:engl1001:2017:54
Oleg Catem:ocat3031:engl1001:2017:87
Oleg Catem:ocat3031:math1001:2016:95
Joe Smith:jsmi3031:math1001:2016:59
Paula Dong:pdon1234:math1001:2016:99

Tags: intxtifcodeunitrecordheadermark
3条回答

unit_code = record[2].endswith('1001') 这行给出的是真或假,而不是子字符串

子串使用

if record[2].endswith('1001'):
   unit_code = record[2][:-4]

问题是线路

unit_code = record[2].endswith('1001')

.endswith()函数返回一个布尔值,这就是为什么输出包含“True”和“False”而不是单位代码。我想您的意思是提取单元代码,并测试它是否以“1001”结尾。更像这样:

skipped_header = True
counters_unit_code = {}
with open("inp.txt") as csv_file:
  for line in csv_file:
    if skipped_header:
      skipped_header = False
      continue
    record = line.rstrip().split(':')
    unit_code = record[2]
      if unit_code.endswith('1001'):
        min_mark = int(record[4])
        if unit_code not in counters_unit_code:
          counters_unit_code[unit_code] = 0
        if min_mark < 50:
          counters_unit_code[unit_code] += 1

for unit_code in counters_unit_code:
  print(str(unit_code), counters_unit_code[unit_code])
skipped_header = True
counters_unit_code = {}
with open("inp.txt") as csv_file:
  for line in csv_file:
    if skipped_header:
      skipped_header = False
      continue
    record = line.rstrip().split(':')
    unit_code = record[2]
    min_mark = int(record[4])
    if unicode.endswith('1001'):
      if unit_code not in counters_unit_code:
        counters_unit_code[unit_code]=0
      if min_mark < 50:
        counters_unit_code[unit_code] += 1

for unit_code in counters_unit_code:
  print(str(unit_code),counters_unit_code[unit_code])

相关问题 更多 >

    热门问题