语句

list


list1=[1, 2, 3]

print(len(list1)) #长度 3
print("第一个元素:%s" % (list1[0])) #从0开始获取第一个元素 1
print("最后一个元素:%s" % (list1[-1])) #从-1开始获取最后一个元素 3

list1.append(4) #追加元素到末尾
print("m末尾追加元素:%s"%(list1[-1]))  # 4

list1.insert(1, 1) #向索引1插入1
print(list1)  # [1, 1, 2, 3, 4]

list1.pop() #删除末尾元素
print(list1)  # [1, 1, 2, 3]

list1.pop(1) #删除指定索引位置元素
print(list1)  # [1, 2, 3]

list1[1] = 1 #替换元素
print(list1)  # [1, 1, 3]

list1[2] = "第3个元素"  #list中的数据类型可以不同
list1.append(False)
list1.append([5,6])
print(list1)  # [1, 1, '第3个元素', False, [5, 6]]

tuple

tuple1=(1,) #定义只有一个元素的元组 不能使用 tuple1=(1)这样定义为1这个数
print(tuple1) # (1,)
#tuple一经定义便不能修改,不过不变的是每个元素的指向,而可以修改器内指针元素指向的对象
tuple2=() # 定义一个空元组

因为tuple与list相比不能修改,所以更安全,尽量使用元组

条件语句

if len(tuple2)==0:
    print("空元组")
elif len(tuple2)>0:   # else if的缩写
    print("非空数组")
else:
    print("无效")

对于判断条件中的非零数值、非空字符串、非空list等,就判断为True,否则为False

input

birth=input("birth:")
birth=int(birth)
if birth > 25:
    print("人到中年,身不由己")
else:
    print("你还年轻")

input默认导入的为一个字符串 因此需要转换类型为int才能进行与数字进行比较

for循环

for x in list1: #遍历列表
    print(x)

for x in range(1,10): 
    print(x)

break continue

break用于提前退出循环
continue用于跳过当前这次循环

for x in range(1,10):
    if x==5:
        break
    print(x)
    
    for x in range(1,10):
    if x==5:
        continue
    print(x)

不要滥用break和continue,容易逻辑分差太多而出错

dict

dict1={"lyy":25, "wtt":20}
dict1[None] = 10
dict1['Adam'] = 67
print(dict1[None]) # 10
print(dict1) #{'lyy': 25, 'wtt': 20, None: 10, 'Adam': 67}

#判断key是否存在  key in dict
if "lyy" in dict1:
    print(dict1["lyy"])   #25

print(dict1.get("eee", "placehoder")) #placehoder  获取key如果没有就返回None或自指定的value

dict1.pop("lyy")  #pop删除指定键
if "lyy" in dict1:
    print(dict1["lyy"])
else:
    print("lyy不存在")  #不存在
    

dict1[(1,)] = "name"  #用元组作为key
print(dict1[(1,)])  #name
#虽然元组也是不可变对象 但是元素不能为list等可变对象
dict1[(1,[1,2])] = "name"  #报错  unhashable type: 'list'

dictkey必须为不可变对象,例如字符串,整数等,而list是可变的不能作为key

和list比较,dict有以下几个特点:
查找和插入的速度极快,不会随着key的增加而变慢;
需要占用大量的内存,内存浪费多。
而list相反:
查找和插入的时间随着元素的增加而增加;
占用空间小,浪费内存很少。

补充知识:

dict()函数 用于创建一个字典,返回一个字典

class dict(**kwarg)  # **kwargs -- 关键字
class dict(mapping, **kwarg)  # mapping -- 元素的容器
class dict(iterable, **kwarg) # iterable -- 可迭代对象


dict()                        # 创建空字典
{}
dict(a='a', b='b', t='t')     # 传入关键字
{'a': 'a', 'b': 'b', 't': 't'}
dict(zip(['one', 'two', 'three'], [1, 2, 3]))   # 映射函数方式来构造字典
{'three': 3, 'two': 2, 'one': 1} 
dict([('one', 1), ('two', 2), ('three', 3)])    # 可迭代对象方式来构造字典
{'three': 3, 'two': 2, 'one': 1}

Set

set中不能元素不能重复,因此只能为不可变对象

要创建set需要用list作为输入集合

set1 = set([1, "name", 1])
print(set1)  # {1, 'name'}
set1.add("1")
set1.add(1)
print(set1)  # {1, '1', 'name'}
set1.remove(1)
print(set1)  # {'1', 'name'}