1、有列表['alex',49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量
info = ['alex',49,[1900,3,18]]
name, age, birth_year = info
print(name, age, birth_year) #alex 49 [1900, 3, 18]
2、用列表的insert与pop方法模拟队列
list1 = []
list1.insert(0,'first')
list1.insert(1,'second')
list1.insert(2,'third')
print(list1) #['first', 'first', 'first']
print(list1.pop(0)) #first
print(list1.pop(0)) #second
print(list1.pop(0)) #third
print(list1) #[]
- 用列表的insert与pop方法模拟堆栈
list1 = []
list1.insert(0, 'first')
list1.insert(1, 'second')
list1.insert(2, 'third')
print(list1) #['first', 'second', 'third']
print(list1.pop()) #third
print(list1.pop()) #second
print(list1.pop()) #first
print(list1) #[]
4、实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数以三元组形式加入购物列表,如果输入为空或其他非法输入则要求用户重新输入
msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
list_shop = []
while True:
shop_name = input('请输入想要购买的商品名:').strip()
if shop_name == 'q':
break
else:
if shop_name in msg_dic:
num = input('请输入购买商品个数:').strip()
if num.isdigit():
price_code = msg_dic[shop_name]
list_shop.append((shop_name, price_code, num))
print('购物列表:{}'.format(list_shop))
break
else:
print('请输入正确的数字!')
else:
print('输入商品不存在,请正确输入商品名!')
5、有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
dic_obj = {}
list1 = []
list2 = []
set1 = {11,22,33,44,55,66,77,88,99,90}
for i in set1:
if i > 66:
list1.append(i)
dic_obj['k1'] = list1
elif i < 66:
list2.append(i)
dic_obj['k2'] = list2
print(dic_obj) #{'k2': [33, 11, 44, 22, 55], 'k1': [99, 77, 88, 90]}
6、统计s='hello alex alex say hello sb sb'中每个单词的个数
s = 'hello alex alex say hello sb sb'
res = s.split(' ')
list1 = []
for i in res:
list1.append((i, len(i)))
print(list1) #[('hello', 5), ('alex', 4), ('alex', 4), ('say', 3), ('hello', 5), ('sb', 2), ('sb', 2)]