python基础____学习笔记1( 字符串,列表、元组、字典、集合)

一、基础知识

1.1 Python3.0 开始输入使用 input , 抛弃了raw_input(), 返回字符串

1.2  字符串
   单引号' ' 双引号 " "表示字符串是一样的 长字符串 """ """ 可以跨域多行
   repr() 表示的所有字符为普通字符,字符不再转义
   str() 表示的字符可以被转义
   原始字符串: 对字符串 进行转义, 以r 打头,可以是单引号,双引号 或者三引号将其括起, 但是不能以反斜杠结尾
   例如: 
         r'C:\Program Files\fnord\foo\bar\baz\frozz\bozz'        不需要对\进行转义
         r'C:\nowhere'                                                              不需要对\n进行转义

1.3 字符串转bytes  bytes转字符串,  bytes 转可变长度的bytearrsy
字符串转bytes :  encode  默认使用utf-8
bytes转字符串 :  decode  默认使用utf-8
例:

teststr='ABCD1234'
bytess=teststr.encode()        #或者bytess=bytes(teststr,"UTF-8")
for byte in bytess:
    print(byte)                #输出十进制数
bytesarry=bytearray(bytess)     #将bytes转换为可变的bytes
bytesarry.append(48)           #追加字符'0'
bytesarry.append(49)           #追加字符'1'
bytesarry.append(50)
print(bytesarry.decode())      #输出ABCD1234012

二、序列
序列包含:列表、元组、字典
1.序列切片
   序列索引值从0开始,最后一个值索引值为-1
   numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]   
   取值number[startIndex: startIndex+num] 默认步长为1
   负数索引是从右往左数,-1 表示最后一个值 
   若步长为整数,则第二个索引必须在第一个索引后面,否则 列表为空;   如number[-4:0]  列表为空
   若步长为负数,则第二个索引必须在第一个索引前面,否则 列表为空;   如number[0:4:-1]  列表为空
   若只想取倒数4个数,只需要给定一个数值 numbers[-4::] 
   numbers[::-2]                         #  [10, 8, 6, 4, 2]
   numbers[5::-2]                       #  [6, 4, 2]
   numbers[:5:-2]                       #[10, 8]

2. 序列复制
 不能使用copyednum=numbers  来复制序列, 这样copyednum 指向同一个序列
 copyednum=numbers[:]
 或
 copyednum=numbers.copy()

3.字符串转换为列表,列表转换为字符串
list(str)       将字符串转换为列表
"".join(list)  将列表转换为字符串

4. 列表类似于C 语言的数据,可以访问、赋值、删除


5. 列表操作方法
append 添加元素
clear    清除列表
copy    复制列表
count   统计某个元素出现的次数
extend 将b列表追加至a列表末尾
    追加列表还有2种方式 1.  a=a+b  (效率低 )   2.a[ len(a):] = b;
index 第一次元素出现的位置
insert(index,value)   在索引 index之前插入value    等效 a[index:index]=value
pop   列表顶部删除一个元素
remove(value) 删除第一值为指定值的元素

motorcycles = ['123','honda', 'yamaha', 'suzuki','123','123','123','456','123','789','432']
index=0
while( index < len(motorcycles)):
    if(motorcycles[index]=='123'):
        motorcycles.remove(motorcycles[index])
        if(index != 0):                #删除后索引值序号前移动,不能直接motorcycles.remove('123'),因为删除'123'后,后面的索引值自动向前移动了
            index=index-1
    index=index+1
print(motorcycles)

reverse    列表反序,本身列表已经更改
sort()        列表排序,返回给新的序列,本身序列不变
          sort()可以指定排序规则,sort(key=len)  sort(reverse=true)

6.元组
6.1 元组是不变的序列
      tuple([1, 2, 3])  将序列转换为元组
      即使元组只有一个元素,元组也必须要加上','     (23,)

6.2 命名元组namedtuple
     collections.namedtuple(typename, field_names)   返回一个命名元组类 typename,其中参数的意义如下:

         typename:类名称         field_names: 元组中元素的名称
命名元组是一个类,有两种方式来定义命名元组:

from collections import namedtuple 
User = namedtuple('User', ['name', 'age', 'id'])
或
User = namedtuple('User', 'name age id')

实例化话命令元组类 

user=User('kai',34,'123456‘’)
print(user.name)
print(user.age)
print(user.id)

命名元组的属性和方法

  • 类属性 _fields:包含这个类所有字段名的元组
  • 类方法 _make(iterable):接受一个可迭代对象来生产这个类的实例
#通过类方法 _make() 和一个list创建一个User对象
user = User._make(['kai', 34, '1234'])
print(User._fields)  #('name', 'age', 'id')

命名元组实例的方法

  • 实例方法 _asdict():把命名元组以 collections.OrdereDict 的形式返回,可以利用它来把元组里的信息友好的展示出来

实例方法_replace():用于修改实例的属性

# 使用 _replace() 修改对象属性
user = user._replace(age=22)     # User(name='kai', age=22, id='123456')
# 使用 _asdict()函数把 User对象转换成字典
print( user._asdict() )
#OrderedDict([('name', 'kai'), ('age', 22), ('id', '123456')])

6.3 把字典或列表转换为命名元组

可以把Python的字典转换为命名元组:

dt={'name':'b', 'age':2, 'id':135}
ut=User(**dt)
## User(name='b', age=2, id=135)

2,把列表转换为命名元组

使用map函数,调用命名元组类的_make函数,把列表转换为命名元组的列表
 

from collections import namedtuple
User = namedtuple('User', 'name age id')
list_users=map(User._make,[('u1',23,1001),('u2',21,1002),('u3',25,1003),])
for user in list_users:
    print(user.name,user.age,user.id)

#u1 23 1001
#u2 21 1002
#u3 25 1003
map() 函数语法:
   map(function, iterable, ...) 
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

def square(x) :            # 计算平方数
    return x ** 2

map(square, [1,2,3,4,5]) 
[1, 4, 9, 16, 25]

3,把命名元组转换为列表

也可以把命名元组转换为list,列表中只有值,而没有字段名称:
 

list(ut) ['b', '2', 135]

   

7.字典
 

dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
#增
dict1['id'] = 110
#删
del dict1['gender']
#改
dict1['age']=22
#查
print(dict1['name']) # Tom
print(dict1.get('name')) # Tom

for key in dict1.keys(): #遍历键值
    print(key,end=' ')
print('\n')
for value in dict1.values():#遍历value
    print(value,end=' ')
print('\n')
for key,value in dict1.items():
    print(key,value)

8. 集合
   创建集合
             有数据集合
                   s1 = {数据1, 数据2, ...}
            无数据集合
                  s1 = set()
   常见操作
           增加数据
              add()
              update()
          删除数据
                 remove()
                 discard()

9. 公共操作
 9.1 运算符

9.2 公共方法
 

fdsa

9.2 容器类型转换
tuple()   将某个序列列转换成元组
list()    将某个序列列转换成列列表

10. 列表推导
 

#简单列表推导
list1 = [i for i in range(10)]
print(list1)
#带if列表推导
list1 = [i for i in range(10) if i % 2 == 0]
print(list1)
#多for 列表推导
list1 = [(i, j) for i in range(1, 3) for j in range(3)]
print(list1)

#列表推导,创建字典
dict1 = {i: i**2 for i in range(1, 5)}
print(dict1) # {1: 1, 2: 4, 3: 9, 4: 16}

#两个列表合并为字典
list1 = ['name', 'age', 'gender']
list2 = ['Tom', 20, 'man']
dict1 = {list1[i]: list2[i] for i in range(len(list1))}
print(dict1)

#字典中提取目标值
counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99}
count1 = {key: value for key, value in counts.items() if value >= 200}
print(count1) # {'MBP': 268, 'DELL': 201}
#集合推导
list1 = [1, 1, 2]
set1 = {i ** 2 for i in list1}
print(set1) # {1, 4}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值