python的变量在使用前不需要先赋值_在赋值Python之前引用的另一个局部变量
我先说:
我知道这是一个经常被问到的问题。我读了其他答案,排除了:
我没有用+=来做作业
我尝试在函数中显式地分配每个变量,以确保它们不是空的,以防函数执行的其他工作失败
它们是不是全局变量,我不希望它们是——它们只是内部变量,我用它们来计算我最终返回的是什么。在## Gets the data from external website - refreshes whenever the programme is called.
## Urllib2 required module
## csv to make life easier handling the data
import urllib2
import csv
import sys
import math
# import sqlite3 #don't need this just now, will probably run Django with MySQL when it comes to it
# import MySQLdb Likewise, don't need this just now.
#python3
import atexit
from time import time
from datetime import timedelta
def secondsToStr(t):
return str(timedelta(seconds=t))
line = "="*40
def log(s, elapsed=None):
print(line)
print(secondsToStr(time()), '-', s)
if elapsed:
print("Elapsed time:", elapsed)
print(line)
print()
def endlog():
end = time()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
def now():
return secondsToStr(time())
start = time()
atexit.register(endlog)
log("Start Program")
def open_external_source():
# Checks if the core file's been modified since the last time we used it - if it hasn't, then we skip all of the file reading stuff.
#need to change this to just pull the headers the first time.
master_data_file = urllib2.urlopen("http://www.football-data.co.uk/mmz4281/1213/E0.csv", "GET")
print master_data_file
headers = master_data_file.info()
last_mod = headers["last-modified"]
settings = open ("settings.csv","r+")
historic_last_mod = settings.readline() #this only works when the setting is a 1 line file
print "Local file version: " + historic_last_mod
print "Server file version: " +last_mod
if last_mod == historic_last_mod :
print "It's the same, file not loaded"
return true
else :
return false
settings.close()
#the if statement's commented out because it was messing up the variables into the function
#if open_external_source == False:
master_data_file = urllib2.urlopen("http://www.football-data.co.uk/mmz4281/1213/E0.csv", "GET")
data = list(tuple(rec) for rec in csv.reader(master_data_file, delimiter=','))
print len(data)
print "printing full file"
print data
league_list = ["Arsenal", "Chelsea", "Liverpool", "Man City", "Man United", "Newcastle", "Newcastle", "Norwich","Reading","Southampton", "Stoke", "Sunderland", "Swansea", "Tottenham", "West Brom", "West Ham", "Wigan"]
league_stats = league_list
#for teams in league_list: - come back to this, will do this as a split and append.
#call the next set of functions to skip the data reading stuff
#This is the data reading section, that puts the data into our system
#If we do proceed, then we redo all of the calculations, and read the data file in again, in case of any corrections, etc.
#Column references:
#Home Goals 4
#Away Goals 5
#Full Time Result 6
#Home Shots 10
#Away Shots 11
#Home Shots on Target 12
#Away Shots on Target 13
#Calculates the average for a given team at home, columns are 4 Home Goals, 5 Away Goa
def CalcAverageHome(team, column, data):
total = 0
count = 0
n=0
for row in data:
if data[count][2] == team:
total += int(data[count][column])
n+=1
count += 1
try:
average = float(total) / n
except ZeroDivisionError:
average = 'Not played'
return average
def CalcAverageAway(team, column, data):
total = 0
count = 0
n=0
for row in data:
if data[count][3] == team:
total += int(data[count][column])
n+=1
count += 1
try:
average = float(total) / n
except ZeroDivisionError:
average = 'Not played'
return average
home_team = "Chelsea"
away_team = "Newcastle"
print "Here's the Average number of goals scored Home"
home_goals = CalcAverageHome(home_team, 4, data)
away_goals = CalcAverageAway(home_team, 5, data)
home_conceded = CalcAverageHome(home_team, 5, data)
away_conceded = CalcAverageAway(away_team, 4, data)
adjusted_home = home_goals * away_conceded
adjusted_away = away_goals * home_conceded
print home_team, home_goals, home_conceded, adjusted_home
print away_team, away_goals, away_conceded, adjusted_away
print "starting to try and work the league averages out here."
def poisson_probability(actual, mean):
# naive: math.exp(-mean) * mean**actual / factorial(actual)
# iterative, to keep the components from getting too large or small:
p = math.exp(-mean)
for i in xrange(actual):
p *= mean
p /= i+1
return p
for i in range (10):
print str((100*poisson_probability(i,adjusted_home)))+"%"
league_list = ["Arsenal", "Chelsea", "Liverpool", "Man City", "Man United", "Newcastle", "Newcastle", "Norwich","Reading","Southampton", "Stoke", "Sunderland", "Swansea", "Tottenham", "West Brom", "West Ham", "Wigan"]
# just assign the league list to the stats for now -
# eventually each team entry will become the first column of a new sublist
def LeagueAverages(data,column):
total = 0
n = 0
for row in data :
string = row[column]
if string.isdigit() == True:
total = total + int(row[column])
n += 1
league_average = float(total) / n
return league_average
print "League home goals average is:", LeagueAverages(data, 4)
print "League away goals average is:", LeagueAverages(data, 5)
print "finished that loop..."
league_stats = []
test_team = "Arsenal"
# Function iterates through the league teams and calculates the averages
# and places them in one long list.
for team in league_list:
league_stats.append(team)
league_stats.append(CalcAverageHome(team, 4, data))
print CalcAverageHome(team, 4, data)
league_stats.append(CalcAverageHome(team, 5, data))
CalcAverageHome(team, 5, data)
league_stats.append(CalcAverageHome(team, 7, data))
CalcAverageHome(team, 7, data)
league_stats.append(CalcAverageHome(team, 8, data))
CalcAverageHome(team, 8, data)
league_stats.append(CalcAverageHome(team, 10, data))
CalcAverageHome(team, 10, data)
league_stats.append(CalcAverageHome(team, 11, data))
CalcAverageHome(team, 11, data)
league_stats.append(CalcAverageHome(team, 12, data))
CalcAverageHome(team, 12, data)
league_stats.append(CalcAverageHome(team, 13, data))
CalcAverageHome(team, 13, data)
# This function should chunk the 'file', as when we run the above code,
# we'll end up with one incredibly long list that contains every team on the same line
def chunker(seq, size):
return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
chunker (league_stats, 9)
final_stats = []
for group in chunker(league_stats, 9):
print repr(group)
final_stats.append(repr(group))
#retrieve a particular value from the final stats array
"""
for row in final_stats:
if data[count][2] == team:
total += int(data[count][column])
n+=1
count += 1
"""
def create_probability_table(hometeam, awayteam, final_stats):
#reads in the home and away sides, calculates their performance adjusted
#ratings and then calculates the likelihood of each team scoring a particular
#number of goals (from 0-10)
#those likelihoods are then combined to provide an 11x11 matrix of probabilities
poisson_array = []
poisson_list_home = []
poisson_list_away = []
goals_home = 0
conceded_home = 0
goals_away = 0
conceded_away = 0
for team in final_stats:
if team == hometeam:
goals_home = team[1]
conceded_home = team [3]
print "home Goals, Home Conceded"
print goals_home, conceded_home
elif team == awayteam:
goals_away = team[2]
conceded_away = team[4]
print "Away Goals, Away Conceded"
print goals_away, conceded_away,
else:
pass
adjusted_goals_home = goals_home * conceded_away
adjusted_goals_away = goals_away * conceded_home
#this section creates the two probability lists for home and away num goals scored
for i in range (10):
poisson_list_home.append = (100*poisson_probability(i,adjusted_goals_home))
poisson_list_away.append = (100*poisson_probability(i,adjusted_goals_away))
print poisson_list_home
print poisson_list_away
for number in poisson_list_home:
for number in poisson_list_away:
probability_table.append(poisson_list_home[number] * poisson_list_away[number])
return probability_table
create_probability_table("Arsenal", "Chelsea", final_stats)
#and this section cross multiplies them into a new list
# for i in range (10):
# print data_frame [0:100] prints to console to provide visual check
master_data_file.close()
当我运行它时,它会抛出一个
^{pr2}$
错误-我不明白为什么!它是在函数开始时定义和分配的。这不是全球性的。在
python的变量在使用前不需要先赋值_在赋值Python之前引用的另一个局部变量相关推荐
- python中变量名有哪些_Python变量范围有哪些?如何在Python中定义变量?
Python变量范围有哪些?如何在Python中定义变量?在Python编程语言中,变量的范围是该变量可见或可访问的那段代码.更准确地说,不是每个程序的每个部分都可以访问所有变量.而且,有时范围也是持 ...
- python环境变量的配置_python基础教程-第一讲-带你进入python的世界
python是一门非常流行的语言,在前段时间网上流传的地产大佬潘石屹宣布要开始学习Python编程,这着实让python又火了一把,但确实反映出python的火热程度 .在2019年12月的世界编程语 ...
- python 循环赋值_计算机二级Python语言程序设计 第2章Python语言基本语法元素
第二章学习知识导图 本章概述:本章目的是了解基础的Python相关知识 考点主要是: 1) 程序的基本语法元素:程序的格式框架.缩进.注释.变量.命名.保留字.数据类型.赋值语句.引用 2) 基本输入 ...
- python调用什么函数实现对文件内容的读取_如何使用python语言中的方法对文件进行读写操作...
在我们使用python语言中的文件时,可以使用open()方法打开文件,close()方法关闭文件,read()方法读取文件内容,write()方法写入内容到文件中.下面利用几个实例说明文件读写方法, ...
- python如何输入数字赋值_三、python语法(定义,赋值,注释,输入输出)
一.变量的定义 1.必须使用英文 2.严格区分大戏小写 3.使用小驼峰的命名方式 4.由数字,字母,下划线,组成,不能以数字作为开头 (java 有数字,字母,下划线,$组成,不能以数字开头) 5. ...
- python中变量名字的第一个字符必须是_基础语法 - 小黑_9527 - 博客园
一.标识符 所谓的标识符就是对变量.常量.函数.类等对象起的名字. 必须说明的是Python语言在任何场景都要严格区分大小写的. 命名规则 1.第一个字符必须是字母中的字母或下划线"_&qu ...
- python定义变量名的时候、需要注意问题_第39p,Python模块的名称空间问题,应该讲完了吧...
大家好,我是杨数Tos,这是<从零基础到大神>系列课程的第39篇文章,第二阶段的课程:Python基础知识:Python中模块与包的概念与使用(下篇). 学习本课程,建议先看一遍:[计算机 ...
- python查看变量内存地址的内置函数是_查看变量内存地址的Python内置函数是____...
查看变量内存地址的Python内置函数是____ 答:id() 产妇乳汁分泌主要依赖于 答:哺乳时吸吮刺激 下列选项中,属于"路径面板"中的工具按钮的是 答:用前景色填充路径 用画 ...
- python语言中函数在调用前必须先定义吗_应该在python中使用函数之前进行定义?...
should the functions be defined before it is used? but why the following code works: def main(): dog ...
最新文章
- array column函数php,php array_column 函数实例应用
- python入门经典例题-Python入门_列表练习题
- MATLAB应用实战系列( 七十五) -图像处理应用 MATLAB实现基于分水岭算法的图像分割 (附matlab代码)
- JDK 16 即将发布,迎来重大改变,新特性速览!
- linux存储库rep 61082,安装informatic过程中的错误
- subList生成的列表和原列表的对比
- namedtuple可命名元组
- 2021-10-28 ACWING826 单链表
- NeoKylin7服务器操作系统安装
- mbr gpt 互转
- 移动医疗仍处于烧钱阶段,海量流量难变现
- 优麒麟这款工具,助你提高60%的工作效率
- 使用 ThreeJS 还原「流浪气球」
- R语言使用order函数对dataframe数据进行排序、基于多个字段(变量)进行升序排序(ASCENDING)
- An error occurred: Cannot write to '/opt/apache-jmeter-5.2.1/bin/jmeterRes/Report1' as folder is not
- 【算法Algorithm】计数(Count)排序
- 网站做竞价推广需要注意什么呢?
- js调用swift相册DEMO(网易新闻)
- nodejs express搭建服务器(爬虫知乎精华帖,个人学习用)四 存储提到的内容的次数
- 梁斌penny_Penny Pinching in the Cloud:如何以10美元的价格运行为期两天的虚拟会议
热门文章
- 如何跨服务器访问html 页面,html页面如何跨域访问另一页面内容,并将部分内容呈现出来?...
- python将图片作为变量_遍历图像列表并在python中将其作为变量分配
- k8s mysql pv_k8s+mysql+pv+pvc+NFS实现mysql容器编排
- 基于JAVA+SpringMVC+Mybatis+MYSQL的流浪宠物救助系统
- Docker:Docker 性质及版本选择 [三]
- JavaScript--动态添加元素
- 德国商业经济金融发展史
- 学习总在继续......
- IModelBinder
- C#3.0新特性 扩展方法