列表的查询判断和遍历

2023-09-16  本文已影响0人  young后知后觉

列表指定元素在列表中是否存在

这个是为了查询元素是否在列表中

格式为:元素 in 列表     如果在,就为true   不在就为false  有点类似于布尔值。

a=[1,2,3,4,5,"你好","hello"]

print(1 in a)   True  元素1 这个数值在列表a当中,所以为True

print(6 in a)   Flase  元素6 不在列表a当中,所以为false

print(7 not in a)   True

print("你" in a)   False   "你"这个字符串不在列表a 当中,所以为False

print("h" in a)   False

遍历:将列表中的元素依次输出

遍历的格式

for 迭代对象 in 列表名:      ( 在列表中将列表的元素依次输出赋值给b迭代对象)   (迭代对象:目前学到的是列表和字符串) 

     print()

for b in a  0        ( 在列表a中将a的元素依次输出赋值给b)

     print(b)

1

2

3

4

5

你好

hello

------------------分割线,下面是直接打印出来的

print("你" in "你好")   True   字符串"你"在字符串"你好"当中,所以为True。这个"你好"的字符串与上面的列表a没有关系

print("h" in "hello")  True  字符串"h"在字符串"hello"当中,所以为True。这个"hello"字符串与这个上面a没有关系

https://www.bilibili.com/video/BV1wD4y1o7AS?p=52&vd_source=e553c01f981e24e5733f375fab53e7e0

51.列表元素的判断及遍历_哔哩哔哩_bilibili

上一篇 下一篇

猜你喜欢

热点阅读