1.列表合并保留最大长度
import itertools
w, x, y, z = [], [1], [2, 3], [4, 5, 6]
longest_wxyz = itertools.zip_longest(w, x, y, z)
print(list(longest_wxyz))
结果: [(None, 1, 2, 4), (None, None, 3, 5), (None, None, None, 6)]
2.列表元素替换
lst = ['1','2','3']
rep = ['4' if x == '2' else x for x in lst]
print(rep)
结果: ['1', '4', '3']
3.列表进行去重操作
一般的去重操作后是出现乱序的情况
t=['8','7','2','中国','China','中国','1','4']
t=list(set(t))
print(t)
结果: ['China', '4', '中国', '8', '1', '7', '2']
如果既想实现去重,又能保持原有的顺序,可以使用下面的方法
temp=list(set(t))
temp.sort(key=t.index)
print(temp)
结果: ['8', '7', '2', '中国', 'China', '1', '4']
4.列表推导式
#方法1:传统方法
import time
t0=time.time()
ind=[]
for i in range(10000):
sqr_values=i*i
ind.append(sqr_values)
t1=time.time()
print(t1-t0)
0.004066944122314453
#方法2:列表推导式
import time
t0=time.time()
sqr_value=[i*i for i in range(10000)]
t1=time.time()
print(t1-t0)
0.0020749568939208984
5.如何让列表所有元素首字母变大写?
问题:
c=['zz','yy','xx']
c[0:2]=c[0:2].capitalize()
提示错误:
AttributeError: 'list' object has no attribute 'capitalize'
解决:
#方法一
c = ['zz','yy','xx']
c = [string.capitalize() for string in c]
#方法二
c = ['xx', 'yy', 'zz']
c = ' '.join(c).title().split()
#方法三
c = ['xx', 'yy', 'zz']
c = ' '.join(c).title().split() #['Xx', 'Yy', 'Zz']
#方法四
[_.capitalize() for _ in c]
#方法五
c = [_.title() for _ in c]
6.如何合并列表中key相同的字典?
#现有list
list1 = [{a: 123}, {a: 456},{b: 789}]
#合并成
list2 = [{a: [123,456]},{b: [789]}]
from collections import defaultdict
lst = [{'a': 123}, {'a': 456},{'b': 789}]
dic = {}
for _ in lst:
for k, v in _.items():
dic.setdefault(k, []).append(v)
print [{k:v} for k, v in dic.items()]
7.去除列表中的 和空字符
s=['
', 'magnet:?xt=urn:btih:060C0CE5CFAE29A48102280B88943880689859FC
']
上面是目标代码,一个列表,中间有 ,我们现在将其去掉
s=[x.strip() for x in magnet_link]
运行会发现结果为
s=['', 'magnet:?xt=urn:btih:060C0CE5CFAE29A48102280B88943880689859FC']
离我们的要求越来越近了
s=[x.strip() for x in magnet_link if x.strip()!='']
好了,结果出来了
s=['magnet:?xt=urn:btih:060C0CE5CFAE29A48102280B88943880689859FC']
8.字符串和列表互相转换
字符串转为列表
str1 = 'a1b2' ls1 = [str(i) for i in str1]
列表转为字符串
ls2 = ['1','a','2','b'] str2 = ''.join(ls2)
同步遍历多个列表
使用zip()函数
name_list = ['张三', '李四', '王五']
age_list = [54, 18, 34]
for name, age in zip(name_list, age_list):
print(name, ':', age)
运行结果:张三 : 54 李四 : 18 王五 : 34
利用下标
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c', 'd', 'f']
n = 0 for each in list1:
print(each, list2[n])
n += 1
运行结果: 1 a 2 b 3 c 4 d 5 f