Python 列表 元组 字典 集合-简单总结

列表 List = [1 , 2 , 3]            元素值可变的有序表

创建空列表:

            List=[]

增删改:

           List.append(4)                                              [1, 2, 3, 4]

           List.extend([5,6])                                          [1, 2, 3, 4, 5, 6]

           List.insert(1, 5)                                             [1, 5, 2, 3, 4, 5, 6]

           List.pop()                                                      [1, 5, 2, 3, 4, 5]

           List.pop(1)                                                    [1, 2, 3, 4, 5]

           List.remove(3)                                              [1, 2, 4, 5]

           List[1]=6                                                       [1, 6, 4, 5]

append和extend都是对列表的尾部做插入操作,如果要指定位置需使用insert(下标,内容)

pop(下标)会弹出一个返回值,若不需要获取删除的值,也可以使用:del List[下标]

已知元素做删除使用remove(元素值),但使用的时候需要做判定。

元组 Tuple =(1 , 2 , 3)        初始化后就不可变的有序表

创建空元组:

            tuple = ()

只有一个元素时的声明:

           tuple = (1,)

元组中可变类型元素:

           tuple = ('a', 'b', ['A', 'B'])

           t[2][0] = 'X'                                                   ('a', 'b', ['X', 'B'])

指向的list并没有改成别的list, list的元素仍然可变

元组的操作和列表类似。

字典 dict = {'a': 1, 'b': 2, 'c': 3} 

键-值(key-value)存储;键唯一 不可重复 不可变;无序表 无索引

创建空集合:

            dist = {}

如果key重复会覆盖掉其他的,只保留一个:

dict2 = {"name":"张无忌","age":20,"name":"张三丰"}       {"name":"张三丰","age":20}

增删查:

           dict1['d']=4                                                  {'a': 1, 'c': 3, 'b': 2, 'd': 4}

           dict1.setdefault('d',5)                                  {'a': 1, 'c': 3, 'b': 2, 'd': 4}

           dict1.pop('b')                                               {'a': 1, 'c': 3, 'd': 4}

           dict1['c']                                                       3

           dict1['e']                                                       报错 KeyError: 'e'

           dict1.get('c')                                                 3

           dict1.get('e')                                                None  

           dict1.get('e',6)                                             {'a': 1, 'c': 3, 'd': 4, 'e': 6}  

      dict1['d']=4没有键d就添加,若有键d就改写。dict1.setdefault('d',5)没有键d就添加,若有键d则不做任何操作。

      get('e')如果没找到不会报错,会输出None。get('e',6)如果取不到就赋值为6,但不会变更原字典。

判断键是否存在:

           'e' in dict1                                                   False

           dict1.get('e')                                                None

           dict1.get('e', "不存在")                                不存在

           dict1.get('c')                                                3

遍历字典的key-value:

      for x,y in enumerate(dict1):                             输出:a 1 c 3 d 4

          print(x,y,end=" ")

集合 set = {1 , 2 , 3}

set和dict的唯一区别仅在于没有存储对应的value ; 去重 无序表

空集合必须使用set函数:

           set3=set()

如果不使用定义空集合,则会定义为是字典:

          set4={}

          print(type(set4))                                         <class 'dict'>

非空集合定义:

           set1 = {1 , 2 , 3}

           set2 = set([1 , 2 , 3])                                   将列表转换成集合

           set1[1]                                                        TypeError: 'set' object does not support indexing 集合中没有下标,是无序存放数据的

增删:

           set1.add(4)                                                 set([1, 2, 3, 4])                                 

           set1.remove(2)                                           set([1, 3, 4])

           set1.remove(5)                                           报错 KeyError: '5'                         

           set1.discard(5)                                            不会报错

运算:

           set1 - set2                                                  差集 set([4])                   set1.difference(set2)

           set1 | set2                                                  并集 set([1, 2, 3, 4])       set1.union(set2)

           set1 & set2                                                 交集 set([1, 3])              set1.intersection(set2)

           set1 ^ set2                                          对称差集 set([2, 4])   set1.symmetric_difference(set2)

     使用discard和remove都可以删除set当中的元素,区别就是remove的元素在set当中没有的话会报错,而discard不会。

遍历(列表、元组、字典)

  通用遍历: 

          for i in animals:                                          遍历列表元素

          for index,animal in enumerate(animals):   遍历下标+元素

animals =['cat','dog','bee','donkey','horse']
for animal in animals:
    print(animal,end=" ")
print()
for index,animal in enumerate(animals):
    print(index,":",animal)
print()

输出:

       

字典的遍历:

         for k in emp:                                                字典的键

         for k in emp.keys():                                      字典的键

         for k in emp.values():                                   字典的值

         for k,v in emp.items():                                  字典的键,值

         for index,k in emp.enumerate():                   字典的下标,键

# 字典的遍历
emp = {"name":"王大力","sex":"男","age":36}
for k in emp:
    print(k)
print()
# 键
for k in emp.keys():
    print(k)
print()
# 值
for v in emp.values():
    print(v)
print()
# 键值对
for k,v in emp.items():
    print(k,v)
print()
# 下标和键
for k,v in enumerate(emp):
    print(k,v)
print()

# 获取字典的所有键和值
emp = {"name":"王大力","sex":"男","age":36}
print(emp.keys())
print(emp.values())

输出:

      

试一试代码

#coding=utf-8
# 列表
List1 = [1, 2, 3]
List1.append(4)
print List1     # [1, 2, 3, 4]
List1.insert(1, 5)
print List1     # [1, 5, 2, 3, 4]
List1.pop()
print List1     # [1, 5, 2, 3]
List1.pop(1)
print List1     # [1, 2, 3]
List1[1]=6
print List1     # [1, 6, 3]

# 元组
tuple0 = (1)
print type(tuple0)     # <type 'int'>
tuple1 = (1,)
print type(tuple1)     # <type 'tuple'>
tuple2 = ('a', 'b', ['A', 'B'])                    
tuple2[2][0] = 'X'    
print tuple2     # ('a', 'b', ['X', 'B'])

# 字典
dict1 = {'a': 1, 'b': 2, 'c': 3} 
dict1['d']=4
print dict1     # {'a': 1, 'c': 3, 'b': 2, 'd': 4}
dict1.pop('b')
print dict1     # {'a': 1, 'c': 3, 'd': 4}
print dict1['c']     # 3
# print dict1['e']  报错 KeyError: 'e'
print 'e' in dict1     # False
print dict1.get('e')     # None
print dict1.get('e', "不存在")     # 不存在
print dict1.get('c')      # 3

# 集合
set1 = {1 , 2 , 3}
set2 = set([1 , 2 , 3])
print set1     # set([1, 2, 3])
print set2     # set([1, 2, 3]) 将列表转换成集合
# print set1[1]     TypeError: 'set' object does not support indexing 集合中没有下标,是无序存放数据的
set1.add(4)     
print set1     # set([1, 2, 3, 4])
set1.remove(2)     
print set1     # set([1, 3, 4])
print set1 - set2     # 差集 set([4])
print set1 | set2     # 并集 set([1, 2, 3, 4])
print set1 & set2     # 交集 set([1, 3])
print set1 ^ set2     # 对称差集 set([2, 4])


练习

  1. L = [[1, 2, 3, 4], ['a', 'b', 'c'], ['x', 'y', 'z'], [['A', 'B'], ['M', 'N']]]
    • 打印出 3
    • 打印出 a, x
    • 打印出 A, M
    • 将 9 添加进 L
L = [[1, 2, 3, 4], ['a', 'b', 'c'], ['x', 'y', 'z'], [['A', 'B'], ['M', 'N']]]
print L[0][2]
print L[1][0],L[2][0]
print L[3][0][0],L[3][1][0]
L.append(9)
print L

         2.  info = {}

    • 将 xiaohua 的个人信息添加到一个 dict 中,dict 中包括 name, age, sex, score
    • 获取 xiaohua 的年龄
    • 删除 xiaohua 的 score 信息
info = {}
info["name"] = "xiaohua"
info["age"] = "18"
info["sex"] = "male"
info["score"] = "100"
print info.get("age")
info.pop("score")
print info

3.

join()函数

语法:  'sep'.join(seq)

参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串

返回值:返回一个以分隔符sep连接各个元素后生成的字符串

os.path.join()函数

语法:  os.path.join(path1[,path2[,......]])

返回值:将多个路径组合后返回

注:第一个绝对路径之前的参数将被忽略

#对序列进行操作(分别使用' '与':'作为分隔符)
  
>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido
  
  
#对字符串进行操作
  
>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
  
  
#对元组进行操作
  
>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido
  
  
#对字典进行操作
  
>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello
  
  
#合并目录
  
>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'

参考链接:Python中的join()函数的用法

猜你喜欢

转载自blog.csdn.net/zhyue77yuyi/article/details/122469507