join(seq):用于拼接 seq:sequence 一系列
以指定字符串作为分隔符,将seq中所有的元素(的字符串表示)合并为一个新的字符串。
new_str = '-'.join('abc')
print(new_str)
'''
运行结果:
a-b-c
'''
————————分割线————————
列表list 作用:类似于数组,是个“容器” (数组:数组的组合\字母的组合\字符串的组合)
符号:[ ]
列表里允许任意类型的元素(整型,字符串,浮点型,列表,元组,字典,对象),但开发时很少这么干
如:[1,2,3,'aa','bb',[1,2],[8,8,9,9]]
列表的运算符号:
+
l1 = [1,2,3]
l2 = [5,6,7]
l3 = l1+l2
print(l3)
'''
运行结果:
[1, 2, 3, 5, 6, 7]
'''
*
l1 = [1,2]*3
print(l1)
'''
运算结果:
[1, 2, 1, 2, 1, 2]
'''
in not in
result = 3 in [1,2,3,4] #in判断元素是否在列表中
print(result)
result = [3] in [1,2,3,4]
print(result)
result = [3] in [1,2,[3],4]#列表支持嵌套
print(result)
#[[1,2],[6,7,8]]二维列表--->多维列表
result = [3,2] in [1,2,[3,2,1],4]#列表支持嵌套
print(result)
'''
运算结果:
True
False
True
False
'''
is not is
比较地址是否相等
增删改查
查:通过下标找某一元素,通过循环找多个元素
元素获取使用:下标 索引 标号规则同截取
列表也支持切片,列表标号顺序同字符串
list[3] list[3:6] list[-3:-1] list[-5:-1:2]截取结果保存在列表中
l5 = [[1,2],[3,2,1],[4,5]]
print(len(l5))
e = l5[2]
print(e,type(e))
print(e[1])
print(l5[1][1])
'''
运行结果:
3
[4, 5] <class 'list'>
5
2
'''
改:1.找到 2.通过=赋值 3.新的值覆盖原有值
删:
del list[index] delete的缩写
改删综合例子
brands = ['hp','dell','lenovo','mac','神州']
brands[-1]='HASEE'
del brands[2]
print(brands)
'''
运行结果:
['hp', 'dell', 'mac', 'HASEE']
'''
tip:for循环倾向于枚举,while是遍历
tip:continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。continue语句用在while和for循环中。
remove(obj) 删除列表中第一次出现的元素a,返回值是None,如果没找到报异常
pop()弹栈 移除列表中的最后一个元素,返回值是删除的元素
默认删除最后一个元素,也可以指定index删除
返回即弹栈动作
clear() 清空,所有元素全部删除
增:
以下三个都是列表自身函数
list.append() 末尾追加
list.extend() 将一个列表中的每一个元素一次性添加到列表中。类似于列表合并,同“+”
list.insert(num,' ') 在标号num后插入元素,指定位置插入
aotuman = ['托雷基亚','戴拿','欧布','迪迦']
aotuman.insert(2,'泰罗')
print(aotuman)
'''
运行结果:
['托雷基亚', '戴拿', '泰罗', '欧布', '迪迦']
'''
in 应用在字符串判断中,也可以用在列表list=[ ]中
案例
words = ['hello','good','apple','digit']
w = input('请输入一个单词:')
for word in words: #in表示在words列表里的元素字符串word
if w in word: #in表示判断字符串w是否出现在字符串word中,in包含==(等值比较)
print('存在此单词')
break
i=1
for w in ['goods','good','abc','aaaa']:
#for循环拿列表中的字符串逐一比较,循环遍历
print('good' in w) #循环条件判断
print('--->',i)
i+=1
'''
结果:
True
--->1
True
--->1
False
--->1
False
--->1
'''
list002.py错误的地方,产生了漏删
list()函数 将指定的内容转换成列表 ,可迭代的内容可以放到list中
print(list(range(1,10,3)))
s = 'abc'
result = list(s)
print(result)
result = list(10) #TypeError: 'int' object is not iterable
print(result)
#什么是可迭代的:for...in里面可以循环就是可迭代的
'''
运行结果:
[1, 4, 7]
['a', 'b', 'c']
'''
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
sorted(iterable, /, *, key=None, reverse=False) 排序函数
Return a new list containing all items from the iterable in ascending(上升的) order(升序).
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
函数精髓在key
count() 指定元素的个数
reverse() 反转,顺序倒过来