列表

列表定义:[]内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素

特性:

  1.可存放多个值

  2.可修改指定索引位置对应的值,可变

  3.按照从左到右的顺序定义列表元素,下标从0开始顺序访问,有序

创建列表:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
list_test1=['hello',12,'ok']
list_test2=list('abc')
list_test3=list(['hello',12,'ok'])
print(list_test1)
print(list_test2)
print(list_test3) 输出结果:
['hello', 12, 'ok']
['a', 'b', 'c']
['hello', 12, 'ok']

列表常用操作:

索引

list_test1=['hello',12,'ok',[14,19]]
print(list_test1.index('hello'))  #输出结果为:0
print(list_test1.index([14,19]))  #输出结果为:3
print(list_test1.index(19)) #该操作会报ValueError: 19 is not in list,因为index()只能索引一级元素,无法索引子列表的子元素

追加:从最后添加元素

list_test1=['hello',12,'ok',[14,19]]
list_test1.append(1994)
print(list_test1)
list_test1.append('txt')
print(list_test1) 输出结果:
['hello', 12, 'ok', [14, 19], 1994]
['hello', 12, 'ok', [14, 19], 1994, 'txt']

插入:指定位置添加元素

list_test1=['hello',12,'ok',[14,19]]
list_test1.insert(3,'exe')    #数字为索引位置,exe为插入的字符串
print(list_test1)
list_test1.insert(0,'txt')
print(list_test1) 输出结果:
['hello', 12, 'ok', 'exe', [14, 19]]
['txt', 'hello', 12, 'ok', 'exe', [14, 19]]

删除:

pop()不加索引默认是从最后一个元素删除

list_test1=['hello',12,'ok',[14,19]]
list_test1.pop()
print(list_test1)
list_test1.pop(0)
print(list_test1) 输出结果:
['hello', 12, 'ok']
[12, 'ok']

remove()从匹配的第一个开始删除

list_test1=['ok','hello','ok',12,'ok',[14,19]]
list_test1.remove('ok')
print(list_test1) 输出结果:
['hello', 'ok', 12, 'ok', [14, 19]]

长度:列表中一个元素算一个长度,conut()方法用于计算某个元素的个数

list_test1=['hello',12,'ok',[14,19]]
print(len(list_test1))
list_test1=['hello','ok',12,'ok',[14,19]]
print(list_test1.count('ok'))

切片

list_test1=['a','c','f',1,2,3,'2a','3b']
print(list_test1[5])
print(list_test1[3:5])
print(list_test1[1:6:2]) 输出结果:
3
[1, 2]
['c', 1, 3]

循环:通过索引遍历一个列表

l=[1,'a',3,[4,5]]
l_size=len(l)
for index in range(l_size):
value=l[index]
if type(value) is list:
for i in range(len(value)):
print(value[i])
else:
print(value) 输出结果:
1
a
3
4
5

包含:直接遍历一个列表

l=[1,'a',3,[4,5]]
for i in l:
x=i
if type(x) is int:
print(x)
else:
for a in x:
print(a) 输出结果:
1
a
3
4
5

拷贝

list_test1=['a','c','f']
list_test2=list_test1.copy()
print(list_test2) 输出结果
['a', 'c', 'f']

扩展:将另一个list的所有元素依次加到一个list中

list_test1=['a','c','f']
list_test1.extend([1,2,3])
print(list_test1) 输出结果
['a', 'c', 'f', 1, 2, 3]

清空:清除所有的元素

list_test1=['a','c','f']
list_test1.clear()
print(list_test1) 输出结果:
[]

反转

list_test1=['ok','hello','ok',12,'ok',[14,19]]
list_test1.reverse()
print(list_test1) 输出结果:
[[14, 19], 'ok', 12, 'ok', 'hello', 'ok']

排序:列表只能是纯字符串或者是纯数字

list_test1=['a','c','f']
print(list_test1)
list_test1.sort()
list_test1.sort(reverse=True)  #打开反转功能,即倒序
print(list_test1) 输出结果:
['a', 'c', 'f']
['f', 'c', 'a']

元组

元组定义:与列表类似,只不过[]改成()

特性

  1.可存放多个值

  2.不可变

  3.按照从左到右的顺序定义元组元素,下标从0开始顺序访问,有序

创建元组:

tuple_test1 = (11, 'aa', 3, 'bc', 'aa','aa')
tuple_test2 = tuple((11, 22, 33, 44, 55))
print(tuple_test1)
print(tuple_test2) 输出结果:
(11, 'aa', 3, 'bc', 'aa', 'aa')
(11, 22, 33, 44, 55)

元组常用操作:

元组的操作和列表的操作类似,但是由于元组是不可变类型,所以没有添加、删除、插入等操作方法

索引

tupel_test1=('hello',12,'ok',(14,19),['a','b'])
print(tupel_test1.index('hello'))  #输出结果为0
print(tupel_test1.index((14,19)))  #输出结果为3
print(tupel_test1.index(19)) #报错,同list一样,无法索引子元组的元素

切片

tupel_test1=('hello',12,'ok',(14,19),['a','b'])
print(tupel_test1[1])
print(tupel_test1[3][1])
print(tupel_test1[4][0]) 输出结果:
12
19
a

长度

tupel_test1=('hello','ok',12,'ok',(14,19),['a','b'])
print(tupel_test1.count('ok')) 输出结果:
2

循环

tuple_test1=('hello','ok',12,'ok',(14,19))
t_size=len(tuple_test1)
for index in range(t_size):
value=tuple_test1[index]
if type(value) is tuple:
for i in range(len(value)):
print(value[i])
else:
print(value) 输出结果
hello
ok
12
ok
14
19

包含

t=(1,'a',3,[4,5])
t_size=len(t)
for index in range(t_size):
value=t[index]
if type(value) is list:
for i in range(len(value)):
print(value[i])
else:
print(value) 输出结果:
1
a
3
4
5

字典

定义:{key1:value1,key2:value2},key-value结构,key必须可hash,即不可变类型

a=1
b='abc'
c=[1,2]
d=('a','b')
print(hash(a))
print(hash(b))
# hash(c)  #列表不可hash,会抛出一个TypeError错误
print(hash(d)) 输出结果
1
-5597926949654223802
4804482478488461503

特性:

  1.可存放多个值

  2.可修改指定key对应的值,可变

  3.无序,每次print顺序都不一样

创建字典:

person1 = {"name": "bob", 'age':18}
person2 = dict(name='alex', age=19)
person3 = dict({"name": "natasha", 'age':20})
person4 = dict((['name','bob'],['age',10]))
print(person1)
print(person2)
print(person3)
print(person4) 输出结果:
{'name': 'bob', 'age': 18}
{'name': 'alex', 'age': 19}
{'name': 'natasha', 'age': 20}
{'name': 'bob', 'age': 10}

转换成字典:值只能有一个

d5={}.fromkeys(['name','age'],None)
print(d5)
d6={}.fromkeys(['name','age'],['bob',18])
print(d6) 输出结果
{'name': None, 'age': None}
{'name': ['bob', 18], 'age': ['bob', 18]}

更新:有的覆盖,没有的添加,原有的保留

d={'name':'alex'}
d1={'name':'alexbb','age':15}
d.update(d1)
print(d) 输出结果
{'name': 'alexsb', 'age': 15}

转换元组:转换的类型并不是tuble类型,但是可以像tuple一样调用,如for i in d.items:

d={'x':1,'y':1}
print(d.items()) 输出结果
dict_items([('x', 1), ('y', 1)])

转换元组删除

d={'x':1,'y':1}
print(d.items())
d.popitem()
print(d.items()) 输出结果
dict_items([('x', 1), ('y', 1)])
dict_items([('x', 1)])

增加一个键值对:如果键已存在,则不添加不更新

d={'x':1,'y':1}
d.setdefault('x','1')
print(d)
d.setdefault('x','3')
print(d)
d.setdefault('k','aaa')
print(d) 输出结果
{'x': 1, 'y': 1}
{'x': 1, 'y': 1}
{'x': 1, 'y': 1, 'k': 'aaa'}

索引

person1 = {"name": "bob", 'age':18}
print(person1['name']) 输出结果
bob

新增

person1 = {"name": "bob", 'age':18}
person1['sex'] = 'male'
print(person1) 输出结果
{'name': 'bob', 'age': 18, 'sex': 'male'}

删除

person1 = {"name": "bob", 'age':18}
print(person1.pop('name'))
print(person1) 输出结果
bob
{'age': 18}

键、值、键值对

#列出包含的key和value
person1 = {"name": "bob", 'age':18}
print(person1.keys())
print(person1.values()) 输出结果
dict_keys(['name', 'age']) #数据类型为dict_keys
dict_values(['bob', 18]) #数据类型为dict_values #检测是否存在某一个key
print(person1.get('name'))
print(person1.get('abc')) 输出结果
bob
None #没有该key抛出None

循环

person1 = {"name": "bob", 'age':18, 'sex':'male'}
for x in person1.keys():
y = person1[x]
print(x,y) 输出结果:
name bob
age 18
sex male

长度

person1 = {"name": "bob", 'age':18}
print(len(person1)) 输出结果:
2

python基础之列表、元组和字典的更多相关文章

  1. python基础(五)列表,元组,集合

    列表 在python中是由数个有序的元素组成的数据结构,每一个元素对应一个index索引来隐式标注元素在列表中的位置.是python中最常用的一种数据类型.需要注意的是列表中可以有重复相同的数据. 列 ...

  2. python基础语法3 元组,字典,集合

    元组: ========================元组基本方法===========================用途:存储多个不同类型的值定义方式:用过小括号存储数据,数据与数据之间通过逗号 ...

  3. python基础——5(元组、字典、集合)

    上节复习: # 数字类型 # int:py3|py2  long:py2 # float: 3.14 # complex(5, 4) => 5 + 4j num = 12345678901234 ...

  4. 【python基础】之元组 集合 字典

    元组 元组:元组和列表类似.但是元组中的元素是固定的(不能给一个元组添加,删除和替换元素以及重新排序) 1.创建元组 t1 = () #创建一个空元组 t2 = (1, 2, 3) t3 = tupl ...

  5. python基础操作_元组_字典操作

    #元组'''元组是不可变的列表,不能改.取值和列表一样'''tp=(1,2,3)tp1=('127.0.0.1','3307')#元组只有count 和index两个方法.lis=['127.0.0. ...

  6. python学习之列表元组,字典

    list:元素性质可以不一致,元素还可以是list,可类似数组方法进行索引(也可以用负数索引,-1表示最后一个),可用.append('')进行动态增加,可用pop()删除最后一个或者pop(i)删除 ...

  7. python基础学习之元组和字典的功能方法

    什么是元组?(tuple) emmmmmm,这个没必要深究吧,就是一排'元素',一行 格式: a = (1,2,3,4,5,6,7,8,9)用小括号表示的,极为元组. 其有序,且不可更改,可以对比st ...

  8. python 序列结构-列表,元组,字典,字符串,集合

    列表 """ name_list.__add__( name_list.__getslice__( name_list.__new__( name_list.append ...

  9. Python基础数据类型-列表(list)和元组(tuple)和集合(set)

    Python基础数据类型-列表(list)和元组(tuple)和集合(set) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 本篇博客使用的是Python3.6版本,以及以后分享的 ...

  10. python基础之列表list元组tuple

    作者:tongqingliu 转载请注明出处:http://www.cnblogs.com/liutongqing/p/7041763.html python基础之列表list元组tuple 列表li ...

随机推荐

  1. iDempiere 使用指南 采购入库流程

    Created by 蓝色布鲁斯,QQ32876341,blog http://www.cnblogs.com/zzyan/ iDempiere官方中文wiki主页 http://wiki.idemp ...

  2. android libs库中的armeabi-v7a,armeabi和x86

    以下内容转载于:http://blog.csdn.net/liumou111/article/details/52949156 1.区别: 这三者都表示的是CPU类型,早期的Android系统几乎只支 ...

  3. JavaScript 编写随机四位数验证码(大小写字母和数字)

    1.JavaScript编写随机四位数验证码,用到的知识点为: a.Math对象的随机数:Math.random() b.Math对象的取整    :Math.floor() c.处理所需要的下标个数 ...

  4. leetcode: 哈希——two-sum,3sum,4sum

    1). two-sum Given an array of integers, find two numbers such that they add up to a specific target ...

  5. 如何将Twitter的内容导入到SAP CRM和C4C

    Twitter的内容导入SAP CRM Interaction Center呼叫中心 具体步骤查看我的博客Twitter(also Facebook) is official integrated i ...

  6. Selenium入门13 cookie的增删改查

    cookie的增删改查: 查询:get_cookies()查询所有cookie,get_cookie(cookie的name)获取单个cookie 删除:delete_cookie(cookie的na ...

  7. CRUD全栈式编程架构之控制器的设计

    页面 这里界面我采用jquery miniui来做的,当你完全了解了整个设计之后可以轻松切换到其他的js框架,个人认为类似muniui,easyui等等这类可以将web界面做得和winform类似的框 ...

  8. QT学习之QScript

    QT中有解析Json的一个类叫QScript.貌似还有一个QJson,但听说解析的方便性不如QScript,具体没有深入探究,这里仅简单记录一下QScript的使用. 首先,主要使用到的类有QScri ...

  9. POJ-1840 Eqs---二分

    题目链接: https://vjudge.net/problem/POJ-1840 题目大意: 给出一个5元3次方程,输入其5个系数,求它的解的个数 其中系数 ai∈[-50,50]  自变量xi∈[ ...

  10. firewalld 使用简介

    学习apache安装的时候需要打开80端口,由于centos 7版本以后默认使用firewalld后,网上关于iptables的设置方法已经不管用了,想着反正iptable也不会用,索性直接搬官方文档 ...