获取list的下标和值
1 | 'a', 'b', 'c', 'd'] mylist = [ |
删除list中的空字符
1 | list1 = ['1', '','2', '3', ' ', ' 4 ', ' 5', ' ','6 ', '', ' ',None, '7'] |
删除list元素
使用remove、pop和del方法参删除list中的某个元素1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20'a', 'b', 'c', 'd','e','f','g','h'] mylist = [
'a') mylist.remove(
mylist
['b', 'c', 'd', 'e', 'f', 'g', 'h']
0) mylist.pop(
'b'
mylist
['c', 'd', 'e', 'f', 'g', 'h']
del mylist[0]
mylist
['d', 'e', 'f', 'g', 'h']
del mylist[0:2]
mylist
['f', 'g', 'h']
del mylist
mylist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'mylist' is not defined
>>>
计算中位数
1 | def get_median(data): |
将字符串list转换为int
1 | '1', '4', '3', '6', '7'] test_list = [ |
合并、连接字符串list
1 | '192', '168', '0', '1'] test_list = [ |
取多个字符串/list交集
1 | '123','234','1253'] a = [ |
合并字典value值
1 | 0:"hello ", 1:"world"} mydict = { |
注意在python3中reduce需要导入:1
from functools import reduce
列表排列组合
列表排列组合可以使用迭代器模块itertools
列表排列
1 | import itertools |
结果:1
2[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
组合
1 | import itertools |
结果:1
[(1, 2), (1, 3), (2, 3)]
多个列表元素组合:笛卡尔积
两个列表元素两两组合:1
2
3
4
5
6
7
8
9import itertools
l = [1, 2, 3]
l1 = [11, 12, 13]
l2 = [21, 22, 23]
# 笛卡尔积
print(list(itertools.product(l, l)))
print(list(itertools.product(l, repeat=2)))
print(list(itertools.product(l1, l2)))
结果:1
2
3[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
[(11, 21), (11, 22), (11, 23), (12, 21), (12, 22), (12, 23), (13, 21), (13, 22), (13, 23)]
列表倒序遍历
1 | # reverse方法 |
本文标题:Python笔记:List相关操作
文章作者:hiyo
文章链接:https://hiyongz.github.io/posts/python-notes-for-list/
许可协议:本博客文章除特别声明外,均采用CC BY-NC-ND 4.0 许可协议。转载请保留原文链接及作者。