1.len在列表与元组上的使用
names = ['xiaobian', 'dewei', 'xiaowang']
length = len(names)
print(length)
运行结果:3
这里是一个列表。注意书写格式:列表中的每一个元素与前一个元素的逗号之间有一个空格。
len在列表和元组上的使用相同。
len函数可以计算出除了数字类型以外,其它所有数据类型的长度。
2.列表(元组)之间的累加与乘法
例1:
names = ['xiaobian', 'dewei', 'xiaowang']
new_names = names + names
print(new_names)
运行结果:
/Users/llq/PycharmProjects/pythonlearn/pythonlearn/.venv/bin/python /Users/llq/PycharmProjects/pythonlearn/pythonlearn1/1.py
['xiaobian', 'dewei', 'xiaowang', 'xiaobian', 'dewei', 'xiaowang']
进程已结束,退出代码为 0
例2:
names = ['xiaobian', 'dewei', 'xiaowang']
new_names = names * 2
print(new_names)
运行结果:
/Users/llq/PycharmProjects/pythonlearn/pythonlearn/.venv/bin/python /Users/llq/PycharmProjects/pythonlearn/pythonlearn1/1.py
['xiaobian', 'dewei', 'xiaowang', 'xiaobian', 'dewei', 'xiaowang']
进程已结束,退出代码为 0
3.in和not in在列表(元组)中的用法
in是判断某个成员(元素)是否在该数据结构中。
not in就是判断某个成员(元素)是否不在该数据结构中。
例1:
names = ['xiaobian', 'dewei', 'xiaoming']
print(bool('xiaobian' in names))
运行结果:True
例2:
names = ['xiaobian', 'dewei', 'xiaoming']
print(bool('xiaowang' not in names))
运行结果:True
4.代码
是否可以用+=和*=对列表和元组进行操作?
可以的。但是这种方式,想直接通过print输出:是不允许的。
![10f42e3e870c09e1c82293e2d889df13.png](https://img-blog.csdnimg.cn/img_convert/10f42e3e870c09e1c82293e2d889df13.png)
#coding:utf-8
names = ('dewei', 'xiaobian', 'xiaowang')
names_add = names + names
names_c = names * 10
print(names_add)
print(names_c)
print('names_c length is', len(names_c))
names += ('abc',)
print(names)
names *= 10
print(names)
names_list = ['dewei', 'xiaobian']
names_list += ['xiaowang']
print(names_list)
names_list *= 5
print(names_list)
print('dewei' in names_list)
print('dewei' not in names_list)
运行结果:
/Users/llq/PycharmProjects/pythonlearn/pythonlearn/python_list/bin/python /Users/llq/PycharmProjects/pythonlearn/python_list/list_01.py
('dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang')
('dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang')
names_c length is 30
('dewei', 'xiaobian', 'xiaowang', 'abc')
('dewei', 'xiaobian', 'xiaowang', 'abc', 'dewei', 'xiaobian', 'xiaowang', 'abc', 'dewei', 'xiaobian', 'xiaowang', 'abc', 'dewei', 'xiaobian', 'xiaowang', 'abc', 'dewei', 'xiaobian', 'xiaowang', 'abc', 'dewei', 'xiaobian', 'xiaowang', 'abc', 'dewei', 'xiaobian', 'xiaowang', 'abc', 'dewei', 'xiaobian', 'xiaowang', 'abc', 'dewei', 'xiaobian', 'xiaowang', 'abc', 'dewei', 'xiaobian', 'xiaowang', 'abc')
['dewei', 'xiaobian', 'xiaowang']
['dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang', 'dewei', 'xiaobian', 'xiaowang']
True
False
进程已结束,退出代码为 0