Python学习笔记--3list列表练习

1.校验用户名是否存在

users = ['nhy','hhh']
for i in range(5):
    username = input('请输入用户名:')
    #如果用户不存在,说明可以注册,
    #if users.count(username)>0:
   
in username in users:#in 就是判断username在不在users里面
       
print ('用户已经被注册')
    else:
        print('用户未注册,可以注册')
        users.append(username)

#也可以用not in, A不在B里。。

users = ['nhy','hhh']
for i in range(5):
    username = input('请输入用户名:')
    #如果用户不存在的话,就说明可以注册,
    # if users.count(username)>0:
   
if username not in users:  #in就是判断在不在里面
       
print('用户未注册,可以注册')
        users.append(username)
    else:
        print('用户已注册')

2.多维数组

nums=[1,2,3,4,['a','b','c','d','e',['一','二','三']]] #三维数组

#多维数组,有几层就是几维数组

多维数组取值:

nums=[1,2,3,4,['a','b','c','d','e',['一','二','三']],['四','五']] #三维数组
print(nums[4][5][1]) #取二
print(nums[5][2]) #或者print(nums[-1][-1]) #取五

  

3.list循环

users = ['nhy','hhh']
passwords=['3443553','345463','2344543','dsfssad']#实际情况可能不知道有多少人的密码,所以循环的时候用while
#
循环这个list (方法一)
print(len(passwords))#取长度,也就是查看list的元素个数。有多少个密码。
count = 0 #最原始的list取值方式,是通过每次计算下标来获取元素的
while count<len(passwords):
    s=passwords[count]
    print('每次循环的时候',s)
    count+=1

#循环这个list (方法二)
for p in passwords: #for循环直接循环一个list,那么循环的时候就是每次取它的值
   
print('每次循环的值',p)

4.修改list的内容,例如每个元素上加“abc_”

#每个前面加上abc_ 第一种方法
passwords=['3443553','345463','2344543','dsfssad']
index=0
for p in passwords:
    passwords[index] = 'abc_'+p
    index+=1
print(passwords)

#每个前面加上abc_ 第二种方法
passwords=['3443553','345463','2344543','dsfssad']
for index,p in enumerate(passwords):#enumerate 是枚举函数,它会帮你计算下标和元素。
   
print('enumerate每次循环的时候',index,p)

    passwords[index] = 'abc_' + p
print(passwords)

猜你喜欢

转载自www.cnblogs.com/youyou-luming/p/9563349.html