美文网首页
Python 基础语法

Python 基础语法

作者: 沧海一粟谦 | 来源:发表于2018-06-25 10:57 被阅读1次
Anne Hathaway

Python 开发环境搭建

  • Anaconda 安装
  • Sublime 安装

Python 使用缩进方式分割代码块

'''
多行注释
可以多行描述
'''

# 单行注释

for i in range(10):
  if i % 2 == 0:
    print(i)

模块导入

# 导入所有模块
import datetime

datetime.datetime.now()

# 只导入指定部分
from datetime import datetime
datetime.now()

函数

def double(x):
  return x * 2

result = double(3)
print(result)

字符串

# 字符串用单引号、双引号都可以,但需要配对
str1 = 'What's is your name?' #wrong
str2 = "What's your name?"
print("str2=%s, len=%d" % (str2, len(str2)))

异常 (发生意外情况,需要进行处理,否则崩溃)

try:
  print(0 / 0)
except ZeroDivisionError:
  print(u"不能被零除")

列表 (list,类似其他语言数组)

list1 = [1, 2, 3]
list2 = ["str", 0.5, 4, True]
list3 = [list1, list2, []]
print(len(list1))
print(sum(list1))

# 取值赋值
x = list(range(10)) # 生成列表[0, 1, ..., 9]
zero = x[0]
nine = x[-1]
eight = x[-2]
x[0] = -1

# 切取列表
first_three = x[:3] # [-1, 1, 2]
three_to_end = x[3:] # [3, 4, ..., 9]
one_to_four = x[1:5] # [1, 2, 3, 4]
last_three = x[-3:] # [7, 8, 9]
without_first_and_last = x[1:-1] # [1, 2, ..., 8]
copy_of_x = x[:]

# in操作符
1 in [1, 2, 3] # True

# 连接列表
x = [1, 2, 3]
x.extend([4, 5, 6])   # x是[1, 2, 3, 4, 5, 6]

# 不改变原列表
x = [1, 2, 3]
y = x + [4, 5, 6]

# 添加元素
x = [1, 2, 3]
x.append(4)

# 提取值
x1, x2 = [1, 2]
_, x2 = [1, 2]

元组 (tuple, 与列表不一样的地方,不能修改)

my_tuple = (1, 2, 3)
my_tuple[0] = -1

# 元组是通过函数返回多个值的好方法
def sum_and_multi(x, y):
  return (x + y), (x * y)

sp = sum_and_multi(3, 5)

字典 dict

empty_dict = {}
grades = {"Jon": 80, "Carmack": 90}

# 取值
carmack_grade = grades["Carmack"]
sophie_grade = grades["Sophie"] # Error
has_sophie = "Sophie" in grades  # False
sophie_grade = grades.get("Sophie") # None
sophie_grade = grades.get("Sophie", 0) # 0

# 赋值
grades["Jon"] = 95
grades["Sophie"] = 70

# 字典排序
# 按值倒序
result = sorted(grades.items(), key=lambda x: x[1], reverse=True)

# 字典可表示结构化数据
one_post = {
  "post_id": 101,
  "title": u"中美贸易战",
  "post_user_id": 5,
  "tags": [u"新闻", u"美国", u"特朗普"],
}

one_post.keys()
one_post.values()
one_post.items()

集合 set 一组不同的元素

s = set()
s.add(1)
s.add(2)
s.add(2)

x = 2 in s
y = 3 in s

list1 = [1, 2, 3, 1, 2, 3]
set1 = set(list1)

控制流

# 条件语句
if 1 > 2:
  print("no")
elif 2 > 3:
  print("no")
else:
  print("yes")

print("yes") if 7 % 2 == 0 else "no"

# while循环
x = 0
while x < 10:
  print("x = %d" % x)
  x += 1

# for in 更常用
for x in range(10):
  print("x = %d" % x)

# continue, break
for x in range(10):
  if x == 2:
    continue   # 进入下一个迭代
  if x == 5:
    break      # 退出循环  
  print("x = %d" % x)

正则表达式

import re

# 去掉标点符号
string = re.sub("[\s+\.\!\/_,$%^*(+\"\']+|[+——!,。??、~@#¥%……&*()]+", "", contents)

读写文件

#读文件
with open(file_name, "r", encoding="utf-8") as f:
    contents = f.read()

with open(file_name, "w", encoding="utf-8") as f:
    f.write("write content")

统计文章字数出现频率

with open("D:\\APIcloud\\word.txt","r",encoding="utf-8") as f:
    contents = f.read()
    print(contents)
    result_dict={}
    for w in contents:
        if w in result_dict:
            result_dict[w] +=1
        else:
            result_dict[w] =1
    result = sorted(result_dict.items(),key=lambda x:x[1],reverse=True)
    print(result)

相关文章

网友评论

      本文标题:Python 基础语法

      本文链接:https://www.haomeiwen.com/subject/vjneyftx.html