Python帮助|从底部读取文本文件中的数据

时间:2015-12-05 19:55:45

标签: python python-2.7 python-3.x

有人可以查看我的程序吗?这是一个我无法识别的错误,这让我很困惑。另外,请向我解释这个问题,以便我能够理解如何在另一种情况下使用该功能和程序。

input_name = input("\nPlease enter students name » ").strip()
datafile = '1.txt'

while open(datafile, 'r') as f:
    data = {}
    for line in f:
        name, value = line.split('=')
        name = name.strip
        value = str(value)
        data.setdefault(name, []).append(value)
else:
    break
avg = {}
for name, scores in data.items():
    last_scores = scores[-3:]
    avg[name] = sum(last_scores) / len(last_scores)

print("\n", input_name,"'s average score is", avg(input_name))

4 个答案:

答案 0 :(得分:2)

单步

将所有数据读入dict:

data = {}
for line in f:
    name, value = line.split('=')
    name = name.strip()
    value = int(value)
    data.setdefault(name, []).append(value)

data的内容:

{'Chris': [9, 9],
 'John': [6, 4, 5],
 'Sarah': [4, 7],
 'Tanzil': [4, 4, 10, 5, 3],
 'Tom': [2]}

现在你可以计算平均值:

last_scores = data['Tanzil'][-3:]
avg = sum(last_scores) / len(last_scores)


>>> avg
6.0

或所有人的平均值:

avg = {}
for name, scores in data.items():
    last_scores = scores[-3:]
    avg[name] = sum(last_scores) / len(last_scores)

现在avg成立:

{'Chris': 9.0, 'John': 5.0, 'Sarah': 5.5, 'Tanzil': 6.0, 'Tom': 2.0}

显示所有结果:

for name, value in avg.items():
    print(name, value)

打印:

Tanzil 6.0
Chris 9.0
Sarah 5.5
John 5.0
Tom 2.0

或从最高到最低的平均得分排序:

from operator import  itemgetter

for name, value in sorted(avg.items(), key=itemgetter(1), reverse=True):
        print(name, value)

打印:

Chris 9.0
Tanzil 6.0
Sarah 5.5
John 5.0
Tom 2.0

完整计划

input_name = input("\nPlease enter students name » ").strip()
datafile = '1.txt'

with open(datafile, 'r') as f:
    data = {}
    for line in f:
        name, value = line.split('=')
        name = name.strip()
        value = int(value)
        data.setdefault(name, []).append(value)

avg = {}
for name, scores in data.items():
    last_scores = scores[-3:]
    avg[name] = sum(last_scores) / len(last_scores)

print("\n", input_name,"'s average score is", avg[input_name])

答案 1 :(得分:0)

希望这会有所帮助:

with open('demo.txt','r') as f:
    reversedList=reversed(f.read().splitlines())
    print filter(lambda x:'Tanzil' in x,reversedList)[:3]

输出:

['Tanzil = 3', 'Tanzil = 5', 'Tanzil = 10']

答案 2 :(得分:0)

我想以下内容可以帮助您完成任务:

  • 将计数器和总和初始化为0,并以反向顺序
  • 读取文件
  • 拆分该行并检查第一部分是否为必需名称。如果为true,则获取第二部分,并将其添加到总和并递增计数器
  • 当计数器击中3时,打破循环
  • 将总和除以3后打印平均值

    counter, sumTotal = 0, 0
    for line in reversed(open("1.txt").readlines()):
      splitArray = line.split("=")
      if splitArray[0].strip() == name:
        sumTotal = sumTotal + int(splitArray[1].strip())
        counter = counter + 1
      if counter == 3:
        break
    
    if counter == 3:
      print "Average for {0} = {1}".format(name, sumTotal/3)
    else if counter == 0:
      print "Name {0} not found".format(name)
    else:
      print "Name {0} does not have three scores".format(name)
    

答案 3 :(得分:0)

如果你在Linux机上,你可以使用public class MainActivity extends AppCompatActivity { private ListDataSource ds; private ListView listViewToDo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("MainActivity","Attempting to create data source"); try { ds = new ListDataSource(); } catch(Exception e) { e.printStackTrace(); Log.d("MainActivity","Failed to create data source"); } Log.d("Main Activity","Attempting to link empty list view to on screen view"); listViewToDo = (ListView)findViewById(R.id.listOfLists); Log.d("Main Activity","Views linked, Attempting to set adapter to listView"); listViewToDo.setAdapter(new ListDataSourceAdapter(this, ds)); Log.d("Maing Activity","Successfully set Adapter"); } } (向后翻猫) - 反向连接和打印文件。

tac