字典及列表内置方法练习

字典及列表内置方法练习

# 1、有列表['alex',49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量
identifier_list = ['alex',49,[1900,3,18]]
name, age, birthday = identifier_list
birth_year, birth_month, birth_date = birthday
print(name, age, birthday, birth_year, birth_month, birth_date,end="\n\n")

# 2、用列表的insert与pop方法模拟队列

#队列法一:
queue = []
#入队         insert函数无返回值
print(queue)
queue.insert(len(queue),"1")        # queue.insert(len(queue),"1") 返回值为None
print(queue)
queue.insert(len(queue),"2")
print(queue)
queue.insert(len(queue),"3")
print(queue)
#出队: .pop函数返回值类型为删除的元素
queue.pop(0)                       # queue.pop(0) 返回值为列表中第一个元素 作用:删去第一个元素
print(queue)
queue.pop(0)
print(queue)
queue.pop(0)
print(queue,end="\n\n")

#队列法二:(第二种方法更直观,类似于一个通道)
queue = []
#入队:
print(queue)
queue.insert(0,"1")
print(queue)
queue.insert(0,"2")
print(queue)
queue.insert(0,"3")
print(queue)
#出队
queue.pop()
print(queue)
queue.pop()
print(queue)
queue.pop()
print(queue,end= "\n\n")

# 3. 用列表的insert与pop方法模拟堆栈
stack = []
# 压栈
print(stack)
stack.insert(len(stack),"1")
print(stack)
stack.insert(len(stack),"2")
print(stack)
stack.insert(len(stack),"3")
print(stack)
# 出栈
stack.pop()
print(stack)
stack.pop()
print(stack)
stack.pop()
print(stack,end="\n\n")



# 4、简单购物车,要求如下:
# 实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数以三元组形式加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  
msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
list = []
while True:
    goods_name = input("请输入商品名(输Q退出):")
    if goods_name == "q" or goods_name == "Q":
        print("欢迎下次光临!")
        break
    goods_num = input("请输入购买数量:")
    if goods_name in msg_dic and goods_num.isdigit():
        num = int(goods_num)
        good_1 = (goods_name, num, num*msg_dic.get(goods_name))
        list.append(good_1)
        print(f"当前您的购物列表:{list}\n")
    else:
        print("输入有误,请重新输入!\n")
        print(f"当前您的购物列表:{list}")



# 5、有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中
# 即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
dic = {}
list = [11,22,33,44,55,66,77,88,99,90]
dic.setdefault("k1",[])         #此处不可写成dic.setdefault("k1",None),初始值必须是空列表,不然无法调用.append()
dic.setdefault("k2",[])
for i in list:
    if i > 66:
        dic["k1"].append(i)     #如果无dic.setdefault("k1",[]),则这种写法是不对的
    else:
        dic["k2"].append(i)
print(dic)


# 6、统计s='hello alex alex say hello sb sb'中每个单词的个数
s='hello alex alex say hello sb sb'
s_list = s.split()
dic = {}
for i in s_list:
    if i in dic:
        dic[i] += 1
    else:
        dic[i] = 1
print(dic)

 

猜你喜欢

转载自www.cnblogs.com/zhubincheng/p/12462827.html