9. python 列表、元组、字典

简介:

1.列表

a = ['a', 'b', 'c', 'abc']

## append  末尾追加

a.append('hello')

print (a)

['a', 'b', 'c', 'abc', 'hello']

## pop 末尾删除

a.pop()

print (a)

['a', 'b', 'c']

## index   索引

print(a[0],a[1])

('a', 'b')

print (a.index('b'))

1

## insert     插入

a.insert(0, 'ajing')

print a

['ajing', 'a', 'b', 'c', 'abc']

a.insert(3, 'lili')

print a

['a', 'b', 'c', 'lili', 'abc']

## remove   删除(一次只能删除最前面的一个)

a.remove('abc')

print (a)

['a', 'b', 'c']

## sort  排序

a.sort()

print a

['a', 'abc', 'b', 'c']

## reverse  反序

a.reverse()

print a

['abc', 'c', 'b', 'a']

2. 切片

## 打印a所有元素

print a[:]

['a', 'b', 'c', 'abc']

## 打印1到最后

print a[1:]

['b', 'c', 'abc']

## 打印1-2

print a[1:3]

['b', 'c']

备注:切片[1:3]取到的最后一位数字,是[1:3]最后一位数字(3)减1

##  间隔打印(步长)

b = range(10)

print b[0:7:2]

[0, 2, 4, 6]

##  反向切片

print a[-1]

print a[-4]

print a[:-1]

print a[-3:]

结果:

abc

a

['a', 'b', 'c']

['b', 'c', 'abc']

3.元组

列表和元组很相似,列表是可变的,元组是不可变的

## 字符串转换成元组:

str1 = 'abcdefghigklmn'

print (tuple(str1))

('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g', 'k', 'l', 'm', 'n')

## 元组 a

a = ('a', 'b', 'c', 'abc', 'hello')

单个元组的时候要注意加逗号

b = ('mn',)

print (type(b))

<type 'tuple'> (类型是元组)

否则python解析器不会识别为 tuple 类型。

##  元组方法:

count   和   index

### count 统计指定元组内相同元素的个数

c = ('a', 'b', 'c', 'a', 'a','k','e')

print a.count('a')

3 (个)

### index 索引(返回某个元素的下标)

print c.index('k')

5 (第5个位置)

注:索引的元素不在元组内的时候报 ValueError 的错误。

4.字典

字典 同很多语言一样是 key:value 这种形式

字典是另一种可变容器模型,可存储任意类型的对象。

字典的每个键值对(key => value)用冒号(:)分割,每个对之间用逗号(,)分割,

整个字典包含在{}(大括号)中

字典赋值有三种方式:

k = {'name':'tiantian', 'age':'10', 123:'abc'}

d = dict(a=1,b=2,c=3)

e = dict([('name','lie'),('age',20)])

字典有很多常用的方法:

## clear  清空字典

e.clear()

## get  获取对应key的value,值不存在返回none

print  (k.get('name'))

'tiantian'

print (k.get('xxx'))

None

字典中没有这个key和value,则返回None

## setdefault  获取对应的key的value,若值不存在,可以自定义值

print (k.setdefault('name'))

'tiantian'

print (k.setdefault('name', 'didi'))

'didi'

print (k.setdefault('xxx'))

None

print (k.setdefault('xxx', 'beijing'))

'beijing'

## keys  获取字典中的所有key,并组成列表

print (k.keys)

['age', 123, 'name']

## iterkeys   获取字典中所有key的对象

print (k.iterkeys())

<dictionary-keyiterator object at 0x00000000026B5F48>

## values   获取字典中所有value,并组成列表

## itervalues 获取字典中所有values的对象

print (k.values())

['10', 'abc', 'tiantian']

print (k.itervalues())

<dictionary-valueiterator object at 0x0000000002585F98>

##  iteritems   遍历

##  items 遍历

print (k.iteritems())

<dictionary-itemiterator object at 0x0000000002705F98>

print (k.items())

[('age', '10'), (123, 'abc'), ('name', 'tiantian')]

【iteritems() 比 items() 更好的利用资源】

for x, y in k.iteritems():

print (x, y)

返回单个元组:

('age', '10')

(123, 'abc')

('name', 'tiantian')

## pop 删除字典中指定keys以及他的value

k.pop('name')

print k

返回:{'age': '10', 123: 'abc'}

5.字典的高级操作

操作一:将列表元素赋value后,组成字典

f = ['a', 'b', 'c', 'd']

m = {}

n = m.fromkeys(f, 123)  (或者:n = dict.fromkeys(f, 123),同理)

print (n)

返回:

{'a': 123, 'c': 123, 'b': 123, 'd': 123}

操作二:将两个列表合为字典

f1= ['a', 'b', 'c', 'd']

f2 = [1, 2, 3, 4]

dict_test = dict(zip(f1, f2))

print (dict_test)

返回:

{'a': 1, 'c': 3, 'b': 2, 'd': 4}

操作三:把第一个字典,增加到第二个字典(合并字典)

k = {'name':'tiantian', 'age':'10', 123:'abc'}

dict_test.update(k)

print dict_test

返回:

{'a': 1, 'c': 3, 'b': 2, 'd': 4, 'age': '10', 123: 'abc', 'name': 'tiantian'}

操作四:对字典进行排序

mm = dict( a=1, b=2, c=3, d=4)

print (mm)

print sorted(mm.itertiems(), key = lambda d:d[0], reverse = True)

【reverse  True 表示反序,False 表示正序】



本文转自 听丶飞鸟说 51CTO博客,原文链接:http://blog.51cto.com/286577399/1975340

相关文章
|
11小时前
|
Python
Python中字典解包解包到变量
【7月更文挑战第4天】
7 1
|
11小时前
|
Python
Python中字典 直接解包
【7月更文挑战第4天】
9 3
|
2天前
|
开发者 Python
震撼!深入理解Python数据类型后,我才明白为什么大神都用列表推导式
【7月更文挑战第2天】Python列表推导式是编程效率提升的秘密武器。它以简洁的一行代码替代循环和条件判断,创建新列表。不仅代码量减少、执行效率高,还提升了可读性和可维护性。列表推导式允许抽象复杂逻辑,支持嵌套,使问题解决更专注。掌握这一特性,让你的Python代码更“Pythonic”,向大神级别迈进!**
|
2天前
|
大数据 程序员 Python
Python数据类型大变身!掌握列表推导式与生成器,编程效率翻倍不是梦
【7月更文挑战第2天】在Python中,列表推导式和生成器是提升效率的利器。列表推导式以简洁方式处理循环和条件,如将偶数平方化简为一行代码,提高代码可读性。生成器则按需生成数据,减少内存占用,适合处理大数据。通过`yield`函数实现惰性求值,有效避免内存溢出。掌握这两者,能优化Python编程体验。
|
2天前
|
C++ Python
揭秘!Python高手都在用的数据类型秘籍,列表推导式让你告别繁琐循环
【7月更文挑战第2天】Python的列表推导式是高手必备技巧,它让复杂的循环简化为一行代码,提升代码的可读性和效率。例如,要计算数字列表的平方,传统循环需使用`for`和`append()`,而列表推导式只需`[number ** 2 for number in numbers]`。此外,它还能结合条件表达式,如筛选并平方偶数:`[number ** 2 for number in numbers if number % 2 == 0]`。学会列表推导式,让你的Python代码更优雅、更易维护。
|
2天前
|
存储 程序员 Python
惊!Python数据类型竟藏着这些黑科技?列表推导式让你代码秒变炫酷!
【7月更文挑战第2天】Python的列表推导式是编程中的亮点,它以一行代码实现循环与条件判断,创建新列表。例如,要计算数字列表的平方,传统方法需循环,而列表推导式只需`[number ** 2 for number in numbers]`。它还能结合if语句筛选元素,如取偶数平方。嵌套使用时,能处理复杂数据结构,如展平并筛选偶数。列表推导式是Pythonic的体现,提升效率,简化代码。
|
2天前
|
Python
Python中的解包字典
【7月更文挑战第2天】
5 1
|
3天前
|
Python 容器
python 元组、列表解包
【7月更文挑战第1天】
8 1
|
4天前
|
存储 索引 Python
经验大分享:python中字典详解
经验大分享:python中字典详解
|
4天前
|
存储 索引 Python
经验大分享:python中字典详解
经验大分享:python中字典详解