Python地理数据处理 二:Python基础知识



1.编写执行代码

  我所用的是IDLE,这是Python安装完成后提供的一个简单的开发环境。IDLE存在两种窗口:shell窗口和编辑窗口。shell窗口是交互式窗口,键入代码并立即获得结果;编辑窗口可以在空文件里编写代码,并在使用Run执行之前,需要将文件保存为 .py 扩展名的文件,运行结果将在shell窗口显示。
  Python的语法高亮显示非常有用,让你分辨出关键字、内置函数、字符串和错误,并且可以使用Tab命令补全。因为Python脚本是一个纯文本文件,如果不想用,也可以不使用IDLE,可以使用PyCharm(非常强大的编辑器,但缺点就是运行速度慢,容易卡顿)、Spyder、PyScripter和Jupyter Notebook(网页的形式,比较好用)

2.脚本结构

  内置模块 :

# Import the random module and use it to get a random number
>>> import random
>>> random.gauss(0,10) 
1.8370967215077911

  Python脚本是没有分号和花括号的,它是使用回车键来结束一行代码和一个代码块,并使用缩进来代替花括号,因而增强了代码的可读性。Python也是需要区分大小写的语言,所有错误有可能来自于大小写,在进行编写的时候我们要进行代码的注释,用哈希符号#:# This is comment

3.变量

  Python不同于其他编程语言,如C++或者java,你需要声明变量的类型,但Python是动态语言,意味着运行前不会检查变量的类型,于是,你可以储存你想要的任何数据类型。即便如此,当你使用的方式和它储存的数据不一致时,将出现错误。

>>> m = 15 # “=”表示赋值
>>> q = 'Hello World'
>>> msg = q + m     #字符串和整数相加,类型不一致
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    msg = q + m
TypeError: can only concatenate str (not "int") to str

  文件打开的两种方式对比:

>>> myfile = open'E:\Google chrome\GIS with python\cities.csv'>>> fn = 'E:\Google chrome\GIS with python\cities.csv'
>>> myfile = open(fn)

4.数据类型

4.1 布尔型

  0、None关键字、空白字符串、空列表、元组集和字典解析为False(区分大小写),其他所有都解析为True。

>>> print(True or False)
True
>>> print(not False)
True
>>> print(True and False)
False
>>> print(True and not False)
True

4.2 数值型

Version :Python 3.9.1,使用旧版本的Python 2.x 会出现一些问题
>>> print(27 / 7) # Integer (Python 2.7) or floating point (Python 3.x) math
3.857142857142857
>>> print(27.0 / 7.0) # Floating point math in both
3.857142857142857
>>> print(27 / 7.0) # Floating point math in both
3.857142857142857
>>> print(27 // 7)  # Force integer point math in Python 3.x
3

数值类型转换:
  浮点型到整数的转换是截取,而不是按照指定位数进行四舍五入。

# Convert between integer and float
>>> print(float(27))
27.0
>>> print(int(27.9))
27

四舍五入方法:

>>> print(round(27.9))  # 使用round函数 
28

4.3 字符串

  字符串是文本值,可以用单引号或双引号创建字符串。

>>> sql = "SELECT * FROM cities WHERE country = 'China'" # 字符串中包含不同的引号
>>> print(sql)

如果你需要在字符串中包含相同类型的引号来描绘,可以使用:“\”

>>> 'Don\'t panic!' # 此时输出有双引号
"Don't panic!"
>>> print('Don't panic!')
      
SyntaxError: invalid syntax

>>> print('Don\'t panic!')
Don't panic!

4.3.1 连接字符串

  连接两个字符串,最快速的方法就是使用“+”:

>>> k = 'Beam me up ' + 'Scotty'   # 两个字符串的连接,美国俚语
>>> print(k)
Beam me up Scotty

  对于多个字符串,用format方法更好,并且如果想在字符串中多次插入元素,可以在多个位置使用相同的占位符。

>>> print('I wish I were as smart as {0} {1}'.format('Albert', 'Einstein'))  # 使用占位符中的索引,按指定顺序格式化字符串

I wish I were as smart as Albert Einstein

>>> print('I wish I were as smart as {1}, {0}'.format('Albert', 'Einstein'))

I wish I were as smart as Einstein, Albert

4.3.2 转义字符

  其中“\n”表示新的一行,“\t”表示缩进:

>>> print('Title:\tThe Gadfly\nAuthor:\tEthel Lilian Voynich')
Title:	The Gadfly
Author:	Ethel Lilian Voynich

  在Windows中“\”作为路径分隔符,一般单独的“\”不是“\”

>>> import os
>>> print(os.path.exists('d:\temp\cities.csv'))  # 此文件确实存在,但却无法访问
False
>>> print('d:\temp\cities.csv')  # “\t”被视为缩进符
d:	emp\cities.csv  

>>> # 有三种方法可以解决这个问题
print(os.path.exists('d:/temp/cities.csv')) # 使用正斜杠

True
>>> print(os.path.exists('d:\\temp\\cities.csv')) # 使用反双斜杠

True
>>> print(os.path.exists(r'd:\temp\cities.csv')) # 使用前缀字符串r告诉Python忽略转义字符串,更方便

True

4.4 列表和元组

  列表是通过索引访问元素的有序集合,第一个元素索引为0,第二个元素索引为1,以此类推。元素不一定是相同的数据类型。由"[ ]"创建一个空列表。

>>> data = [10, 'Bob', 'yellow', -15, 'cat']
>>> print(data)
[10, 'Bob', 'yellow', -15, 'cat']
>>> print(data[0])
10
>>> print(data[2])
yellow

  可从列表尾端开始偏移,最后一个元素的索引为 -1:

>>> print(data[-1])
cat
>>> print(data[-3])
yellow

  可以提供起点和终点的索引来提取切片或子列表。其中,终点索引对应的元素不包括在返回值中。

>>> print(data[1:3])  # 3为终点索引
['Bob', 'yellow']
>>> print(data[-4:-1]) # -1为终点索引
['Bob', 'yellow', -15]

  可以使用索引在列表中改变单个值或者切片:

>>> data[2] = 'blue'
>>> print(data)
[5, 'Bob', 'blue', -15, 'cat']

>>> data[0:2] = [6, 'Jack']
>>> print(data)
[6, 'Jack', 'blue', -15, 'cat']

  使用append可以添加一个元素到列表的末尾,用del来删除一个元素:

>>> data.append('dog')
>>> print(data)
[6, 'Jack', 'blue', -15, 'cat', 'dog']
>>> del data[1]
>>> print(data)
[6, 'blue', -15, 'cat', 'dog']

  元组也是按照顺序排列的元素集合,但是一旦初始化,就无法更改。元组用圆括号,而不是方括号。

>>> data = (6, 'Bob', 'yellow', -15, 'cat')
>>> print(len(data))
5
>>> print(6 in data)
True
>>> print('Mary' in data)
False

  一旦初始化,将无法更改,所以当数据可能发生改变时,选用列表,而不是元组。

>>> data[0] = 10
Traceback (most recent call last):
  File "<pyshell#55>", line 1, in <module>
    data[0] = 10
TypeError: 'tuple' object does not support item assignment

4.5 集合

  集合是无序元素的集合,但每一个值只能出现一次,使得从列表中删除重复元素变得简单。列表中有两个13,但集合中只有一个13:

>>> data = set(['book', 6, 13, 13, 'movie'])
>>> print(data)
{
    
    'movie', 'book', 13, 6}

  添加新值,若其已存在于集合中,就会被忽略:

>>> data.add('movie')
>>> data.add('game')
>>> print(data)
{
    
    6, 13, 'book', 'movie', 'game'}

  集合不是有序的,所以不能访问特定的元素,但可以检查集合中是否存在某元素:

>>> print(13 in data)
True

  可以合并(union)(联合)集合或查找两个集合中共同包含的元素(intersection)(求交):

>>> info = set(['6', 6, 'game', 42])
>>> print(data.union(info))
{
    
    6, 42, 13, 'book', 'movie', 'game', '6'}
>>> print(data.intersection(info))
{
    
    'game', 6}

  确定列表中是否包含重复项是从列表中创建集合,检查集合和列表的长度是否相同。如果不相同,则有重复项。

4.6 字典

  字典是索引的集合,除了不像列表的偏移,其他与列表和元组类似,可以选择称为“”的索引值。键可以是数字、字符串或其他数据类型,因此可以引用它们的值。用花括号创建一个新的字典:

>>> data = {
    
    'color': 'red', 'lucky number': 42, 1: 'one'}
>>> print(data)
{
    
    'color': 'red', 'lucky number': 42, 1: 'one'}
>>> print(data[1])
one
>>> print(data['lucky number'])
42

  添加、更改、删除元素(与列表一样):

>>> data[5] = 'candy'
>>> print(data)
{
    
    'color': 'red', 'lucky number': 42, 1: 'one', 5: 'candy'}

>>> data['color'] = 'green'
>>> print(data)
{
    
    'color': 'green', 'lucky number': 42, 1: 'one', 5: 'candy'}

>>> del data[1]
>>> print(data)
{
    
    'color': 'green', 'lucky number': 42, 5: 'candy'}

  也可以测试某个键是否存在于字典中:

>>> print('color' in data)   # Check if a key is in the dictionary
True 

  当不知道数据是什么时,这是一个储存数据的强大的方式。如,需要记住地理数据集中的每一个文件的空间范围,但每次运行脚本时,数据列表就发生变化。可以创建一个字典,用文件名作为键,对应的空间范围作为值,这些信息将可以在脚本中使用。

5. 控制流

  控制流时改变代码执行顺序的概念

5.1 if 语句

  if和else语句以冒号结尾,且代码会缩进:

n = 1
if n == 1:
    print('n equals 1')
else:
    print('n does not equal 1')
n equals 1

  取消缩进:

n = 1
if n == 1:
    print('n equals 1')
else:
    print('n does not equal 1')
print('This is not part of the condition')
n equals 1
This is not part of the condition

  测试多个条件:

n = 0
if n == 1:
    print('n equals 1')
elif n == 3:
    print('n does not equal 3')
elif n > 5:
    print('n is greater than 5')
else:
    print('what is n?')
what is n?

  另外一个例子,如果为空白或0时,解析为假:

if '':
    print('a blank string acts like True')
else:
    print('a blank string acts like false')
a blank string acts like false

  如果使用一个包含任何字符的字符串,即使是一个空格,也会解析为真,而不是假。

if [1]:
    print('a non-empty list acts like True')
else:
    print('a non-empty list acts like False')
a non-empty list acts like True

5.2 while语句

n = 0
while n < 5:
    print(n)
    n += 1

5.3 for 语句

  for语句不仅提供序列的遍历,也要提供一个变量名。

names = [ 'Janet', 'Chris','Tami']
for name in names:
    print('Hello {}!'.format(name))
Hello Janet!
Hello Chris!
Hello Tami!

range函数 :
  提供一个数字n,并且它将创建从0到n-1的序列。

n = 0
for i in range(20):
    n += 1
print(n)
20

  阶乘:

n = 1
for i in range(1, 11):
    n = n * i
print(n)
3628800

5.4 break、continue和else

for i in [0, 5, 7, 2, 3]:
    if i == 2:
        print('Found it!')
        break
else:
    print('Could not find 2')
Found it!

6.函数

  当需要重复使用代码的时候,可以考虑常见自己的函数。常见一个函数,需要指定一个名称,并告诉用户所需的参数
  阶乘:

def factorial(n):
    answer = 1
    for i in range(1, n + 1):
        answer = answer * i
    return answer
>>> ans = factorial(10)
>>> print(ans)
3628800

  创建可选参数:

def factorial(n, print_it=False):
    answer = 1
    for i in range(1, n + 1):
        answer = answer * i
    if print_it:
        print('{0}! = {1}'.format(n, answer))
    return answer

  若只用数字调用这个函数,将不会输出,因为print_it默认为False。

>>> ans = factorial(5, True)
5! = 120

将函数保存在.py文件里,然后用import导入函数,并进行调用。

import myfuncs
asn = myfuncs.factorial(5)
print(ans)

7.类

>>> import datetime
>>> datetype = datetime.date
>>> mydate = datetype.today()
>>> print(mydate)
2021-01-23
>>> print(mydate.weekday())
5
>>> newdate = mydate.replace(year=2020)
>>> print(newdate)
2020-01-23
>>> print(newdate.weekday())
3

猜你喜欢

转载自blog.csdn.net/amyniez/article/details/113005346