Python 数据类型

Python 中数据类型主要有四种:列表、元组、字典、集合。

一、列表 List

lists = ['a', 'b', 'c']
# 向列表尾部添加元素,允许重复
lists.append('c')
print(lists)
# 获取列表长度
print(len(lists))
# 在列表指定位置插入元素
lists.insert(0, 'mm')
# 移除列表的尾部元素,类似于队列
lists.pop()
# 连接新的 list
lists.extend([7, 8])
print(lists)

# 使用 for in 遍历列表
for val in lists:
    print(val)

# 根据索引遍历列表
for idx in range(len(lists)):
    print(lists[idx])

二、元组 Tuple

##-*- coding: utf-8 -*

tuples = ('tupleA', 'tupleB', 'tupleC')
print(tuples[0])

# 使用for in 进行遍历元组元素
for item in tuples:
 print (item)

# 使用 index 索引遍历元素
for idx in range(len(tuples)):
    print(tuples[idx])

三、字典 Dictionary

# 定义一个 dictionary
dict = {'zhang':3, 'li':4, 'wang':5}
# 添加一个元素
dict['xiao'] = 2
print (dict)
# 删除一个元素
dict.pop('zhang')
# 查看 key 是否存在
print ('wang' in dict)
# 查看 key 对于的值
print(dict.get('wang'))
# key 不存在输出给定的默认值
print(dict.get('kwang'),999999)

# 遍历dictionary
# 1-遍历 key
for key in dict:
    print(key)

# 2-遍历 value
for value in dict.values():
    print(value)

# 3-遍历 key-value
for key, value in dict.items():
    print(key, ':' ,value)

四、集合 Set

# 集合中不允许有重复元素
set = set(['a', 'b', 'c', 'c'])
# 向集合中添加元素
set.add('d')
# 移除集合中元素
set.remove('c')
print(set)

# 遍历集合,元素是无序,不能通过下标访问
for item in set:
    print (item)

【参考资料】

[1] 廖雪峰, Python 教程.

原文地址:https://www.cnblogs.com/lemonu/p/10159390.html