Python课程设计 第 6 / 52 篇

数据类型-参考答案

作业一

写代码,有如下变量,请按照要求实现每个功能

name = " alberT"
# 1 移除 name 变量对应的值两边的空格,并输出处理结果
print(name.strip())
# 2 判断 name 变量对应的值是否以 "al" 开头,并输出结果
print(name.startswith('al'))
# 3 判断 name 变量对应的值是否以 "T" 结尾,并输出结果
print(name.endswith('T'))
# 4 将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
print(name.replace('l', 'p'))
# 5 将 name 变量对应的值根据 “l” 分割,并输出结果。
print(name.split('l'))
# 6 将 name 变量对应的值变大写,并输出结果
print(name.capitalize())
# 7 将 name 变量对应的值变小写,并输出结果
print(name.lower())
# 8 请输出 name 变量对应的值的第 2 个字符?
print(name[2])
# 9 请输出 name 变量对应的值的前 3 个字符?
print(name[:3])
# 10 请输出 name 变量对应的值的后 2 个字符?
print(name[-2:])
# 11 请输出 name 变量对应的值中 “e” 所在索引位置?
print(name.index('e'))
# 12 获取子序列,去掉最后一个字符。如: albert 则获取 alber
print(name[:-1])

作业二

有列表data=[‘albert’,18,[2000,1,1]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量。

data = ['albert', 18, [2000, 1, 1]]
name = data[0]
age = data[1]
birthday = data[2]
year = birthday[0]
month = birthday[1]
day = birthday[2]

作业三

有如下值集合 [11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中,即: {‘k1’: 大于66的所有值, ‘k2’: 小于66的所有值}

a = {'k1': [], 'k2': []}
c = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
for i in c:
    if i > 66:
        a['k1'].append(i)
    elif i < 66:
        a['k2'].append(i)
print(a)

练习四

  1. 列表l=[‘a’,‘b’,1,‘a’,‘a’],列表元素均为可不可变类型,去重得到新列表,且新列表无需保持列表原来的顺序
  2. 在上题的基础上,保存列表原来的顺序
  3. 有如下列表,列表元素为可变类型,去重,得到新列表,且新列表一定要保持列表原来的顺序
l = [

    {'name': 'albert', 'age': 18, 'sex': 'male'},

    {'name': 'james', 'age': 35, 'sex': 'male'},

    {'name': 'taylor', 'age': 25, 'sex': 'female'},

    {'name': 'albert', 'age': 18, 'sex': 'male'},

    {'name': 'albert', 'age': 18, 'sex': 'male'},

]
l = ['a', 'b', 1, 'a', 'a']

# 1 无序去重
print(set(l))

# 2 有序去重
# 方式一:无需集合
l1 = []
for i in l:
    if i not in l1:
        l1.append(i)
print(l1)
# 方式二:借助集合
l1 = []
s = set()
for i in l:
    if i not in s:
        s.add(i)  # 给集合添加元素
        l1.append(i)
print(l1)

# 字典去重
l = [

    {'name': 'albert', 'age': 18, 'sex': 'male'},

    {'name': 'james', 'age': 35, 'sex': 'male'},

    {'name': 'taylor', 'age': 25, 'sex': 'female'},

    {'name': 'albert', 'age': 18, 'sex': 'male'},

    {'name': 'albert', 'age': 18, 'sex': 'male'},

]
# print(set(l))  # 报错:unhashable type: 'dict'
s = set()
l1 = []
for item in l:
    val = (item['name'], item['age'], item['sex'])
    if val not in s:
        s.add(val)
        l1.append(item)
print(l1)

# 定义函数,既可以针对可以hash类型又可以针对不可hash类型(下一阶段课程)
def func(items, key=None):
    s = set()
    for item in items:
        val = item if key is None else key(item)
        if val not in s:
            s.add(val)
            yield item

print(list(func(l, key=lambda dic: (dic['name'], dic['age'], dic['sex']))))

练习五

使用至少两种方法统计字符串 s=‘hello albert albert say hello world world’中每个单词的个数,结果如:

{'hello': 2, 'albert': 2, 'say': 1, 'world': 2}
s = 'hello albert albert say hello world world'

# 方式一
list1 = s.split()
dict1 = {}
for item in list1:
    if item in dict1:
        dict1[item] += 1
    else:
        dict1[item] = 1
print(dict1)

# 方式二
dict2 = {}
words = s.split()
for word in words:
    dict2[word] = s.count(word)
print(dict2)

# 方式三
dict3 = {}
words = s.split()
for word in words:
    dict3.setdefault(word, s.count(word))
print(dict3)

练习六

实现简易购物程序,要求如下:首先打印商品详细信息,然后请用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入

msg_dic = {
    'apple': 10,
    'tesla': 1000000,
    'mac': 10000,
    'iphone': 8000,
    'chicken': 30,
    'pen': 3,
    'ruler': 5
}
msg_dic = {
    'apple': 10,
    'tesla': 1000000,
    'mac': 10000,
    'iphone': 8000,
    'chicken': 30,
    'pen': 3,
    'ruler': 5
}
goods_list = []
while True:
    for product, price in msg_dic.items():
        print('product: %s, price: %s' % (product, price))
    choice = input('please choose product>>:').strip()
    if choice == 'q':  # user can quit the program by inputting 'q'
        break
    elif choice not in msg_dic:
        print('The product you choose is invalid')
        continue
    else:
        while True:
            count = input('please input the number of the product>>:').strip()
            if not count.isdigit():
                print('The content you input is not number')
                continue
            else:
                goods_list.append((choice, msg_dic[choice], count))
                print(goods_list)
                break