python 学习笔记(1)

1.列表:一个有序的集合(类似其它语言中的数组 具备函数功能)

list = [1,2,3] 
length = len(list) #列表长度
total = sum(list)  #列表求和

#列表截取
x =  range(10) #列表[0,1,2,...9]
x[:3]          #截取前三位 [0,1,2]
x[3:]          #截取三位后的[3,4,..9]
x[-3:]         #截取最后三位[7,8,9]
x[1:5]         #[0,1,2,3,4]

2.元组:与列表类似(用圆括号表示或什么也不加)

tuple1 = (1,7)
tuple2 = 1,7
def sum_product(x, y):
      return (x + y),(x * y)

sp = sum_product(3,3) #(6,9)
s,p = sum_product(3,3) #6,9

3.字典:类似java中的map

grades = { "Tom" : 88 , "Joe" : 95 }

Tom_grade = grades["Tom"]           #取值
Tom_has_grade = "Tom" in grades     #确认是否存在
Kate_grade = grades.get("Kate",0)   #不存在则返回0
Jane_grade = grades.get("No one")   #默认值为None
Num_Student = len(grades)           #字典长度

grades.keys()   #键的列表
grades.values() #值的列表
grades.items()  #元祖的列表
defaultdict的使用

from collections import defaultdict
word_counts = defaultdict(int)
for word in document:
     word_counts[word] += 1

4.集合:类似java中的set

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

x = len(s)   # 2
y = 2 in s   # true
z = 3 in s   # false

5 流程控制语句

 if语句:
if 1 > 2:
     message = "13551"
esif 1 > 3:
     message = "12222"
else:
     message = "121222"

一行语句中的if-then-else
x = "even" if y % 2 == 0 else "odd" 
while循环:
x = 0 
while x < 10
      print x," is less than 10"
      x += 1
for循环:
for x in range(10):
     print x ,"is less than 10" 
复杂循环
for x in range(10):
     if x == 3
          continue; #进入下次迭代
     if x == 5
          break; #完全退出循环
     print x

  

6 . and  or  any all

s = some_function_that_return_a_String()
first_char = s and s[0] # 当s为true(s不为空)时 返回s[0]  
y = a  or b             # 从左到右计算 返回第一个真值 

list1  = [1 , 2 , 3 , 5]
list2  = [1 , {} , 3 , 5]

any(list1) # true
any(list2) # true

all(list1) # true
all(list2) # false

any([])    #true 列表中没有假的元素
all([])    #false  列表中没有真的元素

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值