python-列表list- 元组(tuple)- 集合(set)-字典(dict)-实例代码

python 经常用的数据类型还有列表list- 元组(tuple)- 集合(set)-字典(dict),以下是这四种类型用法的简单示例。

1.列表list        [  ] 元素可变 , 有序

2. 元组(tuple)  ( )  元素不可变,可访问

3.集合 set  { }  元素不可重复,没有索引和位置的概念,  无序

4. 字典dict   {  }  key:value   无序

Python 中组合数据类型-列表list- 元组(tuple)- 字典(di)。

1.list [ ]

list 有序元素集合 元素类型可不同

1.访问 单个访问 l=list[0]  l=[1,3,5,7,9,11,13]

多个访问l[2:5]

2.列表操作

list1+list2  合并连接两个列表

list1*n       重复n次列表内容

len(list1)    返回列表长度(元素个数)

x in list1    检查元素是否在列表中

l1*l2         错

3.长度 len(list1) len(l1)=6

4. 检查元素是否在列表中 x in l1

"""

def main():

# m_list=[1,3,5,‘abc‘,9,‘def‘,13]       #赋值为什么就是什么数据类型 也可以写成  m_list=[]

m_list=[1,3,5,7,9,11,13]       #赋值为什么就是什么数据类型 也可以写成  m_list=[]

print(m_list)                  #输出[1,3,5,7,9,11,13]

print(‘访问第一个元素:{}‘.format(m_list[0]))                 #输出1

print(‘访问最后一个元素:{}‘.format(m_list[-1:]))             #输出[13] 返回的是list

print(‘访问最后一个元素:{}‘.format(m_list[-1]))              # 输出13   返回的是元素

print(‘访问倒数第二个元素:{}‘.format(m_list[-2]))            # 输出def

print(‘访问2-5元素:{}‘.format(m_list[2:5]))                  # 输出3=(5-2)个元素,序号从0开始 不包含5,输出[5,‘abc‘,9]

print(‘不访问最后两个元素:{}‘.format(m_list[:-2]))           # [1, 3, 5, 7, 9]

"""

"""

l1=[1,2,3]

l2=[4,5,6]

print(‘加相当于合并 l1+l2={}‘.format(l1+l2))              #输出[1,2,3,4,5]

print(‘乘相当于重复 l1*2={}‘.format(l1*2))                # 输出[1,2,3,1,2,3]

print(‘得到列表中的元素个数len(l1)={}‘.format(len(l1)))  # 输出3

print(‘元素是否在列表中 {}‘.format(10 in l1))             #输出 False

print(‘元素是否在列表中 {}‘.format(‘abc‘ in l1))         # 输出 False

print(‘元素是否在列表中 {}‘.format(5 in l2))              # 输出 True

i=0

m_list=[]

while i <= 10:

m_list.append(i)

i+=1

print(‘while m_list中的所有元素{}‘.format(m_list))      # 输出[0,1,2,3,4,5,6,7,8,9,10]

for i in range(0, 6):                                 #Pop i in range(0,5)

m_list.pop(i)                                     #remove i in range(0,10)

# m_list.remove(i)

print(‘pop操作i={},m_list={}‘.format(i,m_list))

"""

"""

pop操作i = 0,m_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

pop操作i = 1,m_list = [1, 3, 4, 5, 6, 7, 8, 9, 10]

pop操作i = 2,m_list = [1, 3, 5, 6, 7, 8, 9, 10]

pop操作i = 3,m_list = [1, 3, 5, 7, 8, 9, 10]

pop操作i = 4,m_list = [1, 3, 5, 7, 9, 10]

pop操作i=5,m_list=[1, 3, 5, 7, 9]

"""

"""

remove操作i=0,m_list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

remove操作i=1,m_list=[2, 3, 4, 5, 6, 7, 8, 9, 10]

remove操作i=2,m_list=[3, 4, 5, 6, 7, 8, 9, 10]

remove操作i=3,m_list=[4, 5, 6, 7, 8, 9, 10]

remove操作i=4,m_list=[5, 6, 7, 8, 9, 10]

remove操作i=5,m_list=[6, 7, 8, 9, 10]

remove操作i=6,m_list=[7, 8, 9, 10]

remove操作i=7,m_list=[8, 9, 10]

remove操作i=8,m_list=[9, 10]

remove操作i=9,m_list=[10]

remove操作i=10,m_list=[]

"""

"""

for i in range(11, 20):                                   # 输出0开始不包含10

m_list.append(i)

print(‘for m_list中的所有元素{}‘.format(m_list))     #

"""

2.元组 tuple()

1.元组是结构 列表是顺序
2.元组由不同数据组成  列表由相同数据组成
3.一旦被创建 元素不能被修改
4.(‘red‘,‘blue‘,‘green‘),(2,4,6)
5.与list访问相同
6.表达固定数据项、函数多返回值

# def main():

#     days_tup = (31, ‘abc‘, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

#     day=days_tup[:3]

#     print(‘访问前三个元素{}‘.format(day)) #输出为(31 ‘abc‘ 31)

#     print(type(day))                        #返回的是元组

#     day = days_tup[2]

#     print(‘访问第三个元素{}‘.format(day))  # 输出为30

#     print(type(day))                         #返回的是int

3.集合 set {}
1.无序组合
2.元素不可重复
3.没有索引和位置的概念
4.set()用于集合的生成,返回结果是一个无重复且排序任意的集合
5.用于表示成员间的关系、元素去重

def main():

days_set1 = {1,2,3,4,5}

days_set2 = {4,5,7,8,9,10,}

i=0

for i  in range(i,12):

if i in days_set1:

print(‘i={}在集合days_set1中‘.format(i))

elif i in days_set2:

print(‘i={}在集合days_set2中‘.format(i))

elif i in days_set1-days_set2:

print(‘i={}在days_set1中但不在days_set2中‘.format(i))

elif i in days_set1 & days_set2:

print(‘i={}在days_set1和days_set2交集‘.format(i))

elif i in days_set1 | days_set2:

print(‘i={}在days_set1 days_set2所有元素‘.format(i))

else:

print(‘i={}不在集合两个集合中‘.format(i))

4.字典  增删改查

遍历所有的key  for key in d.keys():

Print(key)

遍历所有的value  for value in d.values():

Print(value)

遍历所有的数据项 for item in d.items():

Print(items)

dict 键-值

字典类型数据通过映射查找数据项

映射: 任意键查找集合中的值的过程

一个键对应一个值

字典是无序的。

# 1.创建变量 增删改查

#2.是否在字典中

d=dict()          #定义一个空变量

print(d)

d[‘egg‘]=2.12     #赋值 输出{‘egg‘: 2.12}

print(d)

d[‘milk‘]=3.15    #增加 输出{‘egg‘: 2.12, ‘milk‘: 3.15}

print(d)

#[‘1‘] 和[1] 不同

d[‘1‘]=3.15    #{‘egg‘: 2.12, ‘milk‘: 3.15, ‘1‘: 3.15}

print(d)

d[1] = 3.15    #{‘egg‘: 2.12, ‘milk‘: 3.15, ‘1‘: 3.15, 1: 3.15}

print(d)

d[‘egg‘] = 5.15   #修改 {‘egg‘: 5.15, ‘milk‘: 3.15}

print(d)

del d[‘egg‘]      #删除 {‘milk‘: 3.15}

print(d)

b_in = ‘milk‘ in d #是否在外汇返佣中 True 集合一样

print(b_in)

def main():

# 月份-天数 字典

month_day_dict = {1: 31,

2: 28,

3: 31,

4: 30,

5: 31,

6: 30,

7: 31,

8: 31,

9: 30,

10: 31,

11: 30,

12: 31}

day_month_dict = {30: {4, 6, 9, 11},

31: {1, 3, 5, 7, 8, 10, 12}}

for month_day_key in  month_day_dict.keys():

print("month_day_dict中的key值遍历{}".format(month_day_key))

for month_day_value in  month_day_dict.values():

print("month_day_dict中的values值遍历{}".format(month_day_value))

for item in  day_month_dict.items():

print("day_month_dict中的item{}".format(item))

print (type(item))

Pass

原文链接:https://blog.csdn.net/aggie4628/article/details/103431800

原文地址:https://www.cnblogs.com/benming/p/12028827.html

时间: 2024-07-30 10:13:28

python-列表list- 元组(tuple)- 集合(set)-字典(dict)-实例代码的相关文章

python 数据类型: 数字Nubmer / 字符串String / 列表List / 元组Tuple / 集合Set / 字典Dictionary

#python中标准数据类型 数字Nubmer 字符串String 列表List 元组Tuple 集合Set 字典Dictionary #单个变量赋值countn00 = '10'; #整数countn01 = '100.0' #浮点countn02 = "双权"; #字符串countn03 = '10'; #数字#print("整数 = "+countn00,"浮点 = "+countn01,"字符串 = "+countn0

Python列表、元组、集合、字典的区别和相互转换

列表.元组.集合.字典的区别   列表 元组 集合 字典 英文 list tuple set dict 可否读写 读写 只读 读写 读写 可否重复 是 是 否 是 存储方式 值 值 键(不能重复) 键值对(键不能重复) 是否有序 有序 有序 无序 无序,自动正序 初始化 [1,'a'] ('a', 1) set([1,2]) 或 {1,2} {'a':1,'b':2} 添加 append 只读 add d['key'] = 'value' 读元素 l[2:] t[0] 无 d['a'] 列表.元

列表、元组、集合、字典的区别

列表          元组            集合          字典英文             list          tuple              set             dict可否读写      读写           只读            读写          读写可否重复        是            是                否            是存储方式        值           值         

Python字符串、列表、元组、集合、字典方法

列表list 1.L.append(object) -> None 在列表末尾添加单个元素,任何类型都可以,包括列表或元组等 2.L.extend(iterable) -> None 以序列的形式,在列表末尾添加多个元素 3.L.insert(index, object) -> None 在index位置处添加一个元素 4.L.clear() -> None 清除列表所有元素,成为空列表 5.L.copy() -> list 获得一个列表副本 6.L.count(A) -&g

Python第二周之字符串,列表,元组,集合,字典

# 字符串 1.定义:str类型的,是字符串.例如: var1 = 'Hello world!' 2.使用: 1.增:+ 2.查:index(str), find(str), in 字符串的常用方法 def main(): print(help(''.isalnum)) str1 = 'hello, world' print(len(str1)) print(str1.capitalize()) print(str1.upper()) print(str1) print(str1.find('o

《Python高性能编程》——列表、元组、集合、字典特性及创建过程

这里的内容仅仅是本人阅读<Python高性能编程>后总结的一些知识,用于自己更好的了解Python机制.本人现在并不从事计算密集型工作:人工智能.数据分析等.仅仅只是出于好奇而去阅读这本书.很多人因为Python不能同时使用多颗CPU(全局解释器锁GIL),而觉得它不能实现高性能.书中有很多介绍避开GIL或者Python虚拟机的方式,例如Cython,PyPy等. 首先我们要说一下时间复杂度,可以帮助我们理解CPython编译器怎么干活: 时间复杂度 在描述算法复杂度时,经常用到o(1), o

python学习之列表、元组、集合、字典随笔

数 据  结 构 一.[列表]操作列表的方法如下:  列表是可变序列,通常用于存放同类项目的集合. list_one = [1, 2, 3, 4, True, False, 'pig', 1, 1, 1, 1, 0, 0] list_two = [1, 8, 10, 50, 400, 1000, 600, 2, 3, 99] # 1.添加元素,在列表的末尾添加一个元素 list_one.append('U') print(list_one) # 2.扩展列表,使用可迭代对象中的所有元素进行扩展

二.列表,元组,集合,字典的基础应用

1.列表的应用(list [ ] 非常适合用于存储在程序运行期间可能变化的数据集) 1.1 range()函数 Experiments = [] for Experiment in range(1,10): Experiments.append(Experiment**2) print(Experiments) >>[1, 4, 9, 16, 25, 36, 49, 64, 81] 1.2 列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素 Experiments =[valu

python 列表、元组、字符串、字典、集合、return等梳理

有必要对这些数据类型及操作做下梳理: 1.列表:增删改查 a.查找: 1 >>> names=["zhang","wang","li","zhao"] 2 #列表天生具有下标,基于下标0,1,2,...进行查找 3 >>> names[1] 4 'wang' 5 #列表的切片,即也是基于下标进行操作 6 >>> names[1:3] 7 ['wang', 'li'] 8 &