list 表:
作用:类似其他语言的数组。 数组:数字的组合 字母的组合 字符串的组合…
符号:列表:[ ]
#声明
names=['jack','tom','lucy','superman','ironman']#列表
computer_brands=[]
#增删改查
#地址
print(id(names))
print(id(computer_brands))
#查:通过下标
#元素获取使用:下标 索引
print(names[0])
print(names[1])
#获取最后一个元素
print(names[-1])
print(len(names))
print(names[len(names)-1])
#获取第一个元素
print(names[-5])
#结合循环
#for i in 'hello':
# print()
print("*********************")
for name in names:
print(name)
#查询names里面有没有保存超人
for name in names: #name=jack name=tom
if name=='superman':
print("有超人在里面")
break
else:
print('没有找到超人在里面!')
#简便 't' in 'they'-----> True False
if'superman'in names: #判断有没有
print('有超人在里面!')
else:
print("没有找到超人在里面!")
输出内容:
5522936
5524096
jack
tom
ironman
5
ironman
jack
*********************
jack
tom
lucy
superman
ironman
有超人在里面
有超人在里面!
#增删改
brands=['hp','dell','thinkpad','支持华为','lenvo','mac','神州']
#改
print(brands)
print(brands[-1])
brands[-1]='HASEE' #赋值 步骤:1.找到 (使用下标) 2.通过=赋值 3.新的值覆盖原有的值
print(brands)
#HUAWEI
# for brand in brands:
# if '华为' in brand:
# brand='HUAWEI'
# print(brands)
for i in range(len(brands)):
#i 是0,1,2,3.....>下标
if '华为' in brands[i]:
brands[i]='HUAWEI'
break
print(brands)
#删除 del 是 delete 的缩写
del brands[2]
print(brands)
#删除 只要是 hp mac 都要删除
print('---------删除------------')
#这种思路不太行
# l=len(brands)
# for i in range(l):
# if 'hp' in brands[i] or 'mac' in brands[i]:
# del brands[i]
#
# print(brands)
#我们采用while循环
l=len(brands)
i=0
while i<1:
if 'hp' in brands[i] or 'mac' in brands[i]:
del brands[i]
l-=1
else:
i+=1
print(brands)
输出内容:
['hp', 'dell', 'thinkpad', '支持华为', 'lenvo', 'mac', '神州']
神州
['hp', 'dell', 'thinkpad', '支持华为', 'lenvo', 'mac', 'HASEE']
['hp', 'dell', 'thinkpad', 'HUAWEI', 'lenvo', 'mac', 'HASEE']
['hp', 'dell', 'HUAWEI', 'lenvo', 'mac', 'HASEE']
---------删除------------
['dell', 'HUAWEI', 'lenvo', 'mac', 'HASEE']
注意:
if 让 in 判断作为一个条件表达式
if ‘a’ in ‘abc’:
pass
if ‘a’ in [‘a’,‘b’,‘c’]:
pass
但是:
for …in 循环条件
for 变量 in 字符串/列表:
pass
#方式二
words=['hello','goods','gooo','world','digit','alpha']
w=input('请输入一个单词:')
if w in words:
print('存在此单词')
'abc' in ['abc','hello','aaaa',...] #内容有没有在列表中存在
'go' in 'good' #判断字符串w 有没有出现在word
for word in words: #''' in [......] 判断内容有没有在列表中存在
if w in word: # w in word'' 判断字符串w有没有出现在word
print('存在此单词!')
break
#这种方式删除的只是word,没用,需要使用下标
for word in words:
if w in word:
del word
break
print(words)
输出内容:
请输入一个单词:go
存在此单词!
['hello', 'goods', 'gooo', 'world', 'digit', 'alpha']
words=['hello','goods','gooo','world','digit','alpha']
w=input('请输入一个单词:')
i=0# 表示下标
l=len(words)
while i <l:
if w in words[i]:
del words[i]
l-=1
continue#跳过下方的代码不执行,继续循环
i+=1
print(words)
输出内容:
请输入一个单词:go
['hello', 'world', 'digit', 'alpha']