列表
例子:
内置函数extend
1 a = [1,2,3]
2 b = [4,5]
3 a.extend(b)
4 print(a)
import numpy as np s1 = [3, 5, 5, 5, 5] print(np.sum(s1)) 运行结果:23
运行结果:[1, 2, 3, 4, 5]
字符串切割成列表
1 a = "abcd"
2 s = list(a)
3 print(s)
运行结果:['a', 'b', 'c', 'd']
1 from functools import reduce 2 3 def add1(x,y): 4 return x + y 5 6 print(reduce(add1,range(1,10)))
运行结果:45
1 # 修改元素 2 str = ["a","b","c","d"] 3 def fun2(s): 4 5 return s +"alvin" 6 7 ret = map(fun2,str) 8 print(ret) 9 print(list(ret))
运行结果:
<map object at 0x01751710>
['aalvin', 'balvin', 'calvin', 'dalvin']
1 # 过滤 2 str = ["a","b","c","d"] 3 def funl(s): 4 if s != 'a': 5 return s 6 7 ret = filter(funl,str) 8 print(ret) 9 print(list(ret))
运行结果:['b', 'c', 'd']
1 # 列表生成式 2 text = [str(x) for x in range(10)] 3 print(text) 4 text2 = [x for x in range(10)] 5 print(text2)
运行结果:['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1 #查找索引 2 a = ["a","b","c","d"] 3 print("b的索引是:%s"% a.index("b"))
运行结果:b的索引是:1
1 #元素出现的次数 2 a = ["a","b","b","c","d"].count("b") 3 print("b出现的次数:%s" % a)
运行结果:b出现的次数:2
1 # 列表删除方法3种 2 3 a = ["a","b","c","d"] 4 #1 5 a.remove("a") 6 a.remove(a[0]) 7 #2 8 b = a.pop(1)# 返回删除的内容 9 print(b) 10 #3 11 del a[0]
python列表中的所有值转换为字符串,以及列表拼接成一个字符串
>>> ls1 = ['a', 1, 'b', 2] >>> ls2 = [str(i) for i in ls1] >>> ls2 ['a', '1', 'b', '2'] >>> ls3 = ''.join(ls2) >>> ls3 'a1b2'
4位数全倒
from itertools import permutations s = list(permutations('1234')) a = [list(i) for i in s] s2 = ["".join(i) for i in a] print(s2)
['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314', '2341', '2413', '2431', '3124', '3142', '3214', '3241', '3412', '3421', '4123', '4132', '4213', '4231', '4312', '4321']