line = '1 2 3 4 5'
fields = line.split()
print fields
对应得到的是字符串分割后的字符 [‘1’,’2’,’3’,’4’,’5’]
total = 0
for field in fields:
total += int(field)
total
输出为:
15
numbers = [int(field) for field in fields]
print numbers
则输出为:
[1,2,3,4,5]
然后
sum(numbers)
输出为:
15
将上述语句写在一行:(fields和line.split()是等价的)
sum([int(field) for field in line.split()])
输出为:
15
首先用exit()命令退出Python窗口,然后用cd命令进入指定文件位置,例如:
默认文件位置便由C:\Users\hugechuanqi转到了C:\Python27,例如:输入以下命令
import os
print os.getcwd()
输出为:
C:\Python27
首先用open()命令打开指定路径的文件,不存在时默认建立一个文件;然后用write()命令写入内容,例如:
f = open('data.txt','w')
f.write('1 2 3 4\n')
f.write('2 3 4 5\n')
f.close()
找到默认路径,会发现多出一个data.txt文件,打开后,内容如下:
若想读取文件内容,只需要先用open()命令打开文件,然后用read()命令读取文件内容即可,如下:
f = open('data.txt')
data = []
for line in f:
data.append([int(field) for field in line.spilt()])
f.close()
data
输出为:
[[1,2,3,4],[2,3,4,5]]
或者直接打印数据变量中的内容,按照行的内容提取:
for row in data:
print row
输出为:
[1,2,3,4]
[2,3,4,5]
首先得导入模块os,然后用模块os中的remove命令删除文件内容,如下:
import os
os.remove('data.txt')
def poly (x,a,b,c):
y = a*x**2 +b*x +c
return y
x = 1
poly(x,1,2,3)
输出为:
6
x = array([1,2,3])
poly(x,1,2,3)
输出为:
array([ 6, 11, 18])
from numpy import arange
def poly(x, a=1, b=2 c=3):
y = a*x**2 + b*x + c
return y
x = arange(10)
print x
输出为:
array([0,1,2,3,4,5,6,7,8,9])
当输入为poly(x),输出为:
array([ 3, 6, 11, 18, 27, 38, 51, 66, 83, 102])
当输入为poly(x, b = 1),输出为:
array([ 3, 5, 9, 15, 23, 33, 45, 59, 75, 93])
import os
os.getpid()
输出为:
9612
os.sep
输出为:
'\\'
Person(object)表示继承自object类;
__init__函数来初始化对象;
self表示对象自身,类似于C、Java里面this
class Person(object):
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def full_name(self):
return self.first + '' + self.last
person = Person('Mertle', 'Sedgewick', 52)
person.first
输出为:
'Mertle'
person.full_name()
输出为:
'Mertle Sedgewick'
person.last = 'Smith'
d={'cats':5,'dogs':2,'pigs':7}
person.critters = d
print person.critters
输出为:
{'cats': 5, 'dogs': 2, 'pig': 7}
url = 'http://blog.csdn.net/dream_angel_z/article/details/47110077'
improt urllib2
ge_csv = urllib2.urlopen(url)
data = []
for line in ge_csv:
data.append(line.split(','))
data[:4]
输出为:
[['\n'],
['<html>\n'],
[' <head>\n'],
[' <link rel="canonical" href="http://blog.csdn.net/dream_angel_z/article/details/47110077"/> \n']]
ge_csv = urllib2.urlopen(url)
import pandas
ge = pandas.read_csv(ge_csv, index_col = 0, parse_dates = Ture)
ge.plot(y='Adj Close')