列表(list)
特点:
翻转字符串:
if __name__ == "__main__": inputwords = input().split(" ") # 翻转字符串 # 假设列表 list = [1,2,3,4], # list[0]=1, list[1]=2 ,而 -1 表示最后一个元素 list[-1]=4 ( 与 list[3]=4 一样) # inputWords[-1::-1] 有三个参数 # 第一个参数 -1 表示最后一个元素 # 第二个参数为空,表示移动到列表末尾 # 第三个参数为步长,-1 表示逆向 inputwords = inputwords[-1::-1] print(inputwords) # 重新组合字符串 output = ‘ ‘.join(inputwords) print(output)
输入:
1 2 3 4 5
输出:
[‘5‘, ‘4‘, ‘3‘, ‘2‘, ‘1‘]
5 4 3 2 1
元组
元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号 () 里,元素之间用逗号隔开。
特点:
a = (1,2,[[3,4,"ab"],5,6]) print(a) a[2][0] = [1,2] print(a)
输出:
(1, 2, [[3, 4, ‘ab‘], 5, 6]) (1, 2, [[1, 2], 5, 6])
序列:str、list、tuple都是序列,特点是可以重复,有顺序,可以用下标访问。总结这三种数据结构的共同语法:
集合(set)
集合(set)基本功能是进行成员关系测试和删除重复元素。集合中的对象是无序的、不重复。
特点:
student = {‘Tom‘, ‘Jim‘, ‘Mary‘, ‘Tom‘, ‘Jack‘, ‘Rose‘} print(student) # 输出集合,重复的元素被自动去掉
字典(dictionary)
列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典是一种映射类型,字典用 { } 标识,它是一个无序的 键(key) : 值(value) 的集合。
特点如下:
字典中的内置函数有:clear()、keys()、values()
直接从键值对序列中构建字典的三种方法
>>> dict1 = dict([(1, "abc"),(2,"123"),("def",2)]) >>> print(dict1) {1: ‘abc‘, 2: ‘123‘, ‘def‘: 2} >>> dict2 = {x: x **2 for x in [1,2,3]} >>> dict2 {1: 1, 2: 4, 3: 9} >>> dict3 = dict(a = 1, b = 2, c = 3) # 这里的a,b,c不可以带引号或者换成其他数据类型,否则提示:keyword can‘t be an expression
>>> dict3
{‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
常见的python数据类型转换(详见链接)
dict(d): 创建一个字典。d 必须是一个 (key, value)元组序列
tuple(s): 将序列 s 转换为一个元组
list(s): 将序列 s 转换为一个列表
chr(x): 将一个整数转换为一个字符
参考链接:https://www.runoob.com/python3/python3-number.html
原文:https://www.cnblogs.com/liliwang/p/12676080.html