Python学习2.2列表操作

L=[123,'spam',1.23]
print(L)
print(len(L))
# 支持切片操作
print(L[1])
print(L[:-2])
L += [4,5,6]
print(L)
# 末尾添加元素
L.append('IN')
print(L)
# 弹出、移除
L.pop(4)
print(L)
L.remove(4)
print(L)
# 排序、翻转
M=['aa','bb','cc']
M.reverse()
print(M)
M.sort()
print(M)
# 边界检查
#print(L[99])
#L[99] = 1

# 嵌套
M = [
        [1,2,3],
        [4,5,6],
        [7,8,9]
    ]
print(M)
print(M[2])
print(M[1][2])

# 列表解析表达式
col2 = [row[1] for row in M]
print(col2)
col2 = [row[1]+1 for row in M]
print(col2)
col2 = [row[1] for row in M if row[1]%2 == 0]
print(col2)

diag = [M[i][i] for i in [0,1,2]]
print(diag)

doubles = {c*2 for c in 'spam'}
print(doubles)
# 括号中的解析语法也可以用来创建产生所需结果的生成器
G = (sum(row) for row in M)
print(next(G))
print(next(G))
print(next(G))
# 内置函数map也可以实现类似功能
print(list(map(sum,M)))
# 3.0中 解析语法也可以用来创建集合和字典
print({sum(row) for row in M})
print({i:sum(M[i]) for i in range(3)})
# 列表、集合和字典都可以用解析来创建
print([ord(x) for x in 'spaam'])
print({ord(x) for x in 'spaam'})
print({x:ord(x) for x in 'spaam'})

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
=================== RESTART: F:\PyCode\Day2对象类型\2.列表操作.py ===================
[123, 'spam', 1.23]
3
spam
[123]
[123, 'spam', 1.23, 4, 5, 6]
[123, 'spam', 1.23, 4, 5, 6, 'IN']
[123, 'spam', 1.23, 4, 6, 'IN']
[123, 'spam', 1.23, 6, 'IN']
['cc', 'bb', 'aa']
['aa', 'bb', 'cc']
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[7, 8, 9]
6
[2, 5, 8]
[3, 6, 9]
[2, 8]
[1, 5, 9]
{'aa', 'pp', 'ss', 'mm'}
6
15
24
[6, 15, 24]
{24, 6, 15}
{0: 6, 1: 15, 2: 24}
[115, 112, 97, 97, 109]
{112, 97, 115, 109}
{'s': 115, 'p': 112, 'a': 97, 'm': 109}
>>> 

猜你喜欢

转载自blog.csdn.net/Lasuerte/article/details/82146834
今日推荐