Python基础学习列表+元组+字典+集合

  • Post category:Python

Python基础学习:列表、元组、字典和集合

列表

列表 是Python中最常用的数据类型之一,用于存储一系列元素。列表的每个元素可以是数字、字符串、布尔值等,甚至可以是其他列表。

定义列表

使用方括号 [] 来定义列表,元素之间用逗号 , 分隔。

fruits = ['apple', 'banana', 'orange']

访问列表元素

可以通过下标来访问列表中的元素,下标从0开始计数。

fruits = ['apple', 'banana', 'orange']
print(fruits[0]) # 输出:'apple'

列表相关操作

  • 添加元素

  • append(): 在列表末尾添加元素

python
fruits = ['apple', 'banana', 'orange']
fruits.append('kiwi')
# fruits 现在为 ['apple', 'banana', 'orange', 'kiwi']

  • insert(): 在指定位置添加元素

python
fruits = ['apple', 'banana', 'orange']
fruits.insert(1, 'kiwi')
# fruits 现在为 ['apple', 'kiwi', 'banana', 'orange']

  • 删除元素

  • remove(): 删除指定元素

python
fruits = ['apple', 'banana', 'orange']
fruits.remove('banana')
# fruits 现在为 ['apple', 'orange']

  • pop(): 删除指定位置的元素,不传入参数时默认删除最后一个元素

python
fruits = ['apple', 'banana', 'orange']
fruits.pop(1) # 删除第二个元素 'banana'
# fruits 现在为 ['apple', 'orange']

  • 修改元素

直接使用下标访问元素,并进行修改

python
fruits = ['apple', 'banana', 'orange']
fruits[1] = 'kiwi'
# fruits 现在为 ['apple', 'kiwi', 'orange']

  • 查找元素

  • index(): 返回指定元素的下标

python
fruits = ['apple', 'banana', 'orange']
index = fruits.index('banana')
# index 现在为 1

  • in: 判断元素是否在列表中,返回布尔值

python
fruits = ['apple', 'banana', 'orange']
is_in = 'banana' in fruits # True

元组

元组 类似于列表,但是它是不可变的,也就是说元组中的元素不能被修改、添加或删除。

定义元组

使用圆括号 () 来定义元组,元组的元素之间用逗号 , 分隔。

foods = ('pizza', 'burger', 'fries')

访问元组元素

可以通过下标来访问元组中的元素,下标从0开始计数。

foods = ('pizza', 'burger', 'fries')
print(foods[0]) # 输出:'pizza'

字典

字典 是Python中另一个非常实用的数据类型,它用于存储键-值对。字典中的键必须是唯一的,值可以是任何数据类型。

定义字典

使用大括号 {} 来定义字典,每个键-值对使用冒号 : 分隔,不同的键-值对之间使用逗号 , 分隔。

contacts = {
    'Alice': 'alice@example.com',
    'Bob': 'bob@example.com',
    'Charlie': 'charlie@example.com'
}

访问字典元素

可以通过键来访问字典中的值。

contacts = {
    'Alice': 'alice@example.com',
    'Bob': 'bob@example.com',
    'Charlie': 'charlie@example.com'
}
print(contacts['Bob']) # 输出:'bob@example.com'

字典相关操作

  • 添加键-值对

直接使用新的键和值将其添加到字典中

“`python
contacts = {
‘Alice’: ‘alice@example.com’,
‘Bob’: ‘bob@example.com’,
‘Charlie’: ‘charlie@example.com’
}

contacts[‘Dave’] = ‘dave@example.com’
# contacts 现在为 {‘Alice’: ‘alice@example.com’, ‘Bob’: ‘bob@example.com’, ‘Charlie’: ‘charlie@example.com’, ‘Dave’: ‘dave@example.com’}
“`

  • 删除键-值对

使用 del 关键字来删除指定的键-值对。

“`python
contacts = {
‘Alice’: ‘alice@example.com’,
‘Bob’: ‘bob@example.com’,
‘Charlie’: ‘charlie@example.com’
}

del contacts[‘Bob’]
# contacts 现在为 {‘Alice’: ‘alice@example.com’, ‘Charlie’: ‘charlie@example.com’}
“`

集合

集合 是一组无序、唯一的元素。集合通过大括号 {} 来定义,元素之间使用逗号 , 分隔。

定义集合

使用大括号 {} 来定义集合。

fruits = {'apple', 'banana', 'orange'}

集合相关操作

  • 添加元素

  • add(): 添加一个元素

python
fruits = {'apple', 'banana', 'orange'}
fruits.add('kiwi')
# fruits 现在为 {'apple', 'banana', 'orange', 'kiwi'}

  • 删除元素

  • remove(): 删除指定元素

python
fruits = {'apple', 'banana', 'orange'}
fruits.remove('banana')
# fruits 现在为 {'apple', 'orange'}

  • discard(): 删除指定元素,如果元素不存在则不抛出异常

python
fruits = {'apple', 'banana', 'orange'}
fruits.discard('banana')
# fruits 现在为 {'apple', 'orange'}

  • 取交集、并集和差集

  • intersection(): 返回与另一个集合的交集

python
fruits1 = {'apple', 'banana', 'orange'}
fruits2 = {'banana', 'kiwi'}
intersection = fruits1.intersection(fruits2)
# intersection 现在为 {'banana'}

  • union(): 返回与另一个集合的并集

python
fruits1 = {'apple', 'banana', 'orange'}
fruits2 = {'banana', 'kiwi'}
union = fruits1.union(fruits2)
# union 现在为 {'apple', 'banana', 'kiwi', 'orange'}

  • difference(): 返回与另一个集合的差集

python
fruits1 = {'apple', 'banana', 'orange'}
fruits2 = {'banana', 'kiwi'}
difference = fruits1.difference(fruits2)
# difference 现在为 {'apple', 'orange'}

示例

示例1:计算员工考勤记录的平均工作时长

from statistics import mean

# 计算平均工作时长函数
def average_work_hours(attendance_records):
    # attendance_records 是一个包含每个员工工作时长的列表
    return mean(attendance_records)

# 示例
attendance_records = [8, 7, 10, 9, 6]
avg_work_hours = average_work_hours(attendance_records)
print(f'员工考勤记录的平均工作时长为:{avg_work_hours}小时')

示例2:统计一个文本字符串中每个单词出现的次数

text = 'This is a sample text. It contains some sample data for demonstration purposes.'

# 将字符串转换为小写,并将标点符号替换为空格,去除多余空格
text = text.lower().replace('.', ' ').replace(',', ' ').replace('  ', ' ').strip()

# 将字符串转换为列表,并去除重复单词,保证统计准确
words = list(set(text.split()))

# 使用字典统计每个单词出现的次数
word_counts = {}
for word in words:
    count = text.count(word)
    word_counts[word] = count

# 输出结果
for word, count in word_counts.items():
    print(f'{word} 出现了 {count} 次')

以上就是 Python 基础学习中关于列表、元组、字典和集合的完整攻略。