python学习笔记-----列表

列表

# 数组:数据类型必须相同; arr = [1,2,3]
# 列表: 可以是不同数据类型的集合

# 1. 列表的定义

l1 = [1,2,3,4,5]
print(l1,type(l1))

l2 = [1, 4.5, 1+2j, "hello"]
print(l2, type(l2))
字符串的特性: 索引, 切片, 连接, 重复, 成员操作符;
students_name = ['harry', 'linux', 'python', 'natasha']

    # 1. 索引
    # 正向索引
    print(students_name[0])
    # 反向索引
    print(students_name[-1])

    # 2. 切片
    print(students_name[::-1])

    #
    s = "hello xiao mi"   # "mi xiao hello"
    print(" ".join(s.split()[::-1]))

    # 3. 重复
    print(students_name*3)

    # 4. 连接
    print(students_name + ['Bob', 'Lilei'])

    # 5. 成员操作符
    print('Bob' in students_name)
    print('linux' in students_name)

    # 6. for循环遍历列表元素
    for student in students_name:
        print("学生姓名:%s" %(student))


    # 7. 列表里面嵌套列表

    goods = [
        ['apple', 2, 100],
        ['banana', 3, 50],
        ['computer', 4000, 13]
    ]
    # 嵌套索引
    print(goods[0][0])

结果:

harry
natasha
['natasha', 'fentiao', 'westos', 'harry']
mi xiao hello
['harry', 'westos', 'fentiao', 'natasha', 'harry', 'westos', 'fentiao', 'natasha', 'harry', 'westos', 'fentiao', 'natasha']
['harry', 'westos', 'fentiao', 'natasha', 'Bob', 'Lilei']
False
True
学生姓名:harry
学生姓名:westos
学生姓名:fentiao
学生姓名:natasha
apple

练习:

假定有下面这样的列表:
    names = ['fentiao', 'fendai', 'fensi', 'apple']
    输出结果为:'I have fentiao, fendai, fensi and apple.'

考察点:
    切片:
    字符串的join方法:
names = ['fentiao', 'fendai', 'fensi', 'apple']
print("I have " + ",".join(names[:-1]) + ' and ' + names[-1])
列表的增加
names = ['fentiao', 'fendai', 'fensi', 'apple']

# append: 追加, 追加元素到列表的最后;
names.append('westos')
print(names)

names.append(['linux', 'R', 'matlab'])
print(names)

# insert: 添加元素到指定索引的前面;
names.insert(0, 'java')
print(names)

# extend: 追加多个元素到列表中;
names.extend(['c', 'C++', 'Go'])
print(names)

结果:

['fentiao', 'fendai', 'fensi', 'apple', 'westos']
['fentiao', 'fendai', 'fensi', 'apple', 'westos', ['linux', 'R', 'matlab']]
['java', 'fentiao', 'fendai', 'fensi', 'apple', 'westos', ['linux', 'R', 'matlab']]
['java', 'fentiao', 'fendai', 'fensi', 'apple', 'westos', ['linux', 'R', 'matlab'], 'c', 'C++', 'Go']
列表的删除
names = ['fentiao', 'fendai', 'fensi', 'apple', 'fendai']

# remove: 删除指定的值
names.remove('fendai')
print(names)

# names.pop(): pop删除指定索引的值, 默认情况删除最后一个元素;
# a = name.pop(), a就是删除的那个元素;
value = names.pop(0)
print(value)
print(names)

# del删除列表元素
# del names[0]
# del names[-1]
# del names[1:]
# del names[:-1]
# del names


# # clear: 清空列表
# names.clear()
# print(names)
列表的修改
names = ['fentiao', 'fendai', 'fensi', 'apple', 'fendai']

# 通过索引, 重新赋值;
names[0] = 'redhat'
print(names)

# 通过切片重新赋值
names[:2] = ['java', 'C']
print(names)
列表的查看
names = ['fentiao', 'fendai', 'fensi', 'apple', 'fendai', 'A', 'a', 'ab', 'Ab']

# 查看指定元素的索引值;
print(names.index('fentiao'))

# 查看指定元素出现的次数;
print(names.count('fendai'))

# 按照指定的ASCII码进行排序的;
names.sort()
print(names)

# 不区分大小写进行排序;
names.sort(key=str.lower)
print(names)

# 列表的反转; 类似于li[::-1]
li = [10, 3, 89, 80]
li.reverse()
print(li)
列表方法练习——用户管理系统
用户登陆系统Version2:
        1). 已知多个用户名和密码分别保存在列表中;
        2). 判断用户名是否存在,
                如果登陆的用户不存在,则报错;;
                如果用户存在, 则判断密码是否正确:
                    如果正确, 输出用户登陆成功;
                    如果不正确, 输出登陆失败;

        3). 为防止黑客暴力破解密码, 登陆最多有3次机会;

代码如下:

names = ['root', 'student']
passwds = ['redhat', 'student']

tryCount = 0
while tryCount < 3:
    tryCount += 1
    inuser = input("用户名:")
    # 1.判断用户是否存在?
    if inuser in names:
        # 2. 判断密码是否正确?
        inpasswd = input("密码:")
        # 找出系统存储的inuser用户的密码;
        index = names.index(inuser)   # inuser='root', index=0
        passwd = passwds[index]     # passwd='redhat'
        if inpasswd == passwd:
            print("%s登陆成功!" %(inuser))
            break
    else:
        print("用户名%s不存在" %(inuser))
else:
    print("尝试次数超过3次!")
列表嵌套操作
import pprint

# pprint.pprint(object,stream=None,indent=1, width=80, depth=None) 
# 输出格式的对象字符串到指定的stream,最后以换行符结束。

li1 = [
    [1, 2, 3],
    [2, 3, 4],
    [3, 4, 5]
]
li2 = [
    [2, 3, 4],
    [1, 2, 3],
    [1, 2, 3]
]

# numpy,  pandas, matplotlib
result = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
]

#  i : 0, 1, 2
for i in range(len(li1)):
    # j: 0, 1, 2
    for j in range(len(li1[i])):
        # [0][0], [0][1], [0][2]
        # [1][0]
        result[i][j] = li1[i][j] + li2[i][j]
pprint.pprint(result)

通过列表实现栈的数据结构
# 栈的工作原理: 先进后出

# 入栈;
# 出栈:
# 栈顶元素:
# 栈长度
# 栈是否为空

# 2. 队列的工作原理: x先进先出
# 入队, 出队, 队头, 队尾, 队列长度, 
# 队列是否为空, 显示队列元素

stack = []

info = """
            栈操作

        # 1). 入栈; 
        # 2). 出栈:
        # 3). 栈顶元素
        # 4). 栈长度
        # 5). 栈是否为空     
"""

while True:

    print(info)

    choice = input("请输入选择:")

    if choice == '1':
        item = input("入栈元素:")
        stack.append(item)
        print("元素%s入栈成功" %(item))
    elif choice == '2':
        # 出栈先判断栈是否为空;
        if  not stack:
            print("栈为空, 不能出栈")
        else:
            # item是弹出的那个元素;
            item = stack.pop()
            print("元素%s出栈成功" %(item))
    elif choice == '3':
        if len(stack) == 0:
            print("栈为空, 无栈顶元素")
        else:
            print("栈顶元素为%s" %(stack[-1]))
    elif choice == '4':
        print("栈长度为%s" %(len(stack)))
    elif choice == '5':
        if len(stack) == 0:
            print("栈为空")
        else:
            print("栈不为空.")
    elif choice == 'q':
        print("欢迎下次使用!")
        break
    else:
        print("请输入正确的选择!")

枚举
# 枚举, 返回列表的索引及对应的元素值;
for i in enumerate(['a', 'b', 'c']):
    print(i,end=' ')


# 返回
(0, 'a') (1, 'b') (2, 'c') 

猜你喜欢

转载自blog.csdn.net/qq_41891803/article/details/81413716