高级数据类型

    科技2022-08-25  89

    列表

    name_list = ["zhangsan", "lisi", "wangwu"] print(name_list[2]) print(name_list.index("wangwu")) #输出格式化字符串 print(name_list) #改 name_list[1] = "李四" #增 name_list.append("王小二") name_list.insert(1, "小美眉") temp_list = ["孙悟空", "猪二哥", "沙师弟"] name_list.extend(temp_list) #删 name_list.remove("wangwu") name_list.pop() name_list.pop(3) name_list.clear() del name_list[1] #计 list_len = len(name_list) #序 name_list.sort() name_list.reverse() #历 for my_name in name_list: print("我的名字叫 %s" % my_name)

    元组

    info_tuple = ("zhangsan", 18, 1.75, "zhangsan") print(info_tuple[0]) print(info_tuple.index("zhangsan")) print(info_tuple.count("zhangsan")) #不输出格式化字符串 for my_info in info_tuple: print(my_info) #这样可以 info_tuple = ("小明", 21, 1.85) print("%s 年龄是 %d 身高是 %.2f" % info_tuple) info_str = "%s 年龄是 %d 身高是 %.2f" % info_tuple print(info_str) print(len(info_tuple))

    字典

    xiaoming = {"name": "小明", "age": 18, "gender": True, "height": 1.75, "weight": 75.5} #字典是无序的 print(xiaoming) print(len(xiaoming_dict)) print(xiaoming_dict["name"]) xiaoming_dict["age"] = 18 xiaoming_dict["name"] = "小小明" xiaoming_dict.pop("name") print(xiaoming_dict) #覆盖 temp_dict = {"height": 1.75, "age": 20} # 注意:如果被合并的字典中包含已经存在的键值对,会覆盖原有的键值对 xiaoming_dict.update(temp_dict) xiaoming_dict.clear() for k in xiaoming_dict: print("%s - %s" % (k, xiaoming_dict[k])) #字典列表1 card_list = [xiaoming,daming] for card_info in card_list: print(card_info) #字典列表2 students = [ {"name": "阿土"}, {"name": "小美"} ] find_name = "张三" for stu_dict in students: print(stu_dict) if stu_dict["name"] == find_name: print("找到了 %s" % find_name) break else: print("抱歉没有找到 %s" % find_name) print("循环结束")

    字符串

    str2 = '我的外号是"大西瓜"' print(str2[5]) for char in str2: print(char) hello_str = "hello hello" print(len(hello_str)) print(hello_str.count("llo")) print(hello_str.index("llo")) print(hello_str.index("abc")) hello_str = "hello world" print(hello_str.startswith("Hello")) print(hello_str.endswith("world")) print(hello_str.find("llo")) print(hello_str.find("abc")) # replace方法执行完成之后,会返回一个新的字符串 # 注意:不会修改原有字符串的内容 print(hello_str.replace("world", "python")) print(hello_str) #整理 poem = ["\t\n登鹳雀楼", "王之涣", "白日依山尽\t\n", "黄河入海流", "欲穷千里目", "更上一层楼"] for poem_str in poem: # 先使用strip方法去除字符串中的空白字符 # 再使用center方法居中显示文本 print("|%s|" % poem_str.strip().center(10, " ")) #整理 poem_str = "登鹳雀楼\t 王之涣 \t 白日依山尽 \t \n 黄河入海流 \t\t 欲穷千里目 \t\t\n更上一层楼" print(poem_str) # 1. 拆分字符串 poem_list = poem_str.split() print(poem_list) # 2. 合并字符串 result = " ".join(poem_list) print(result)
    Processed: 0.024, SQL: 9