Python精选200+Tips:1-5

Pick a flower, You will have a world

运行系统:macOS Sonoma 14.6.1
Python编译器:PyCharm 2024.1.4 (Community Edition)
Python版本:3.12

001 list

列表(list)是 Python 中一种用于存储有序元素的数据结构。以下是列表的基本特性:

  • 有序性:列表中的元素保持插入顺序,可以通过索引访问。
  • 可变性:列表是可变的,可以随时修改、添加或删除元素。
  • 可以包含不同类型的元素:列表可以存储不同类型的数据,包括数字、字符串和其他对象。
  1. list的交、并、差
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

# 交集:两个列表中都存在的元素
intersection = list(set(list1) & set(list2))
# 输出: [3, 4]

# 并集:两个列表中所有不同元素的集合
union = list(set(list1) | set(list2))
# 输出: [1, 2, 3, 4, 5, 6]

# 差集(补集):第一个列表中有而第二个列表中没有的元素
difference = list(set(list1) - set(list2))
# 输出: [1, 2]

# 对称差集:两个列表中不重复的元素
symmetric_difference = list(set(list1) ^ set(list2))
# 输出: [1, 2, 5, 6]
  1. 嵌套list展平
# 使用递归
nested_list = [1, [2, [3, 4], 5], 6, [7, 8]]

def flatten(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            # 递归
            flat_list.extend(flatten(item))
        else:
            flat_list.append(item)
    return flat_list

flattened = flatten(nested_list)
# 输出: [1, 2, 3, 4, 5, 6, 7, 8]


#  生成器递归
def flatten_generator(nested_list):
    for item in nested_list:
        if isinstance(item, list):
            yield from flatten_generator(item)
        else:
            yield item

flattened = list(flatten_generator(nested_list))
# 输出: [1, 2, 3, 4, 5, 6, 7, 8]
  1. 遍历多list
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
for index, (char, number) in enumerate(zip(list1, list2)):
    print(index, char, number)

# 输出
# 0 a 1
# 1 b 2
# 2 c 3
  1. list拷贝
list1 = ['a', 'b', 'd']
list1_copy = list1  # 浅拷贝,和原list一样
list_deepcopy = list1.copy()  # 深拷贝,和原list独立。等价于list_deepcopy = list1[:]
list1[-1] = 88

# 输出
print(list1) # ['a', 'b', 88]
print(list1_copy) # ['a', 'b', 88]
print(list_deepcopy) # ['a', 'b', 'd']
  1. 条件筛选
# 有else,for写后面
numbers = [-10, -5, 0, 5, 10]
result = ["Negative" if num < 0 else "Zero" if num == 0 else "Positive" for num in numbers]

print(result)
# 输出 ['Negative', 'Negative', 'Zero', 'Positive', 'Positive']

# 没有else,for写前面
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

numbers = [1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 17, 18, 19, 20]
filtered_numbers = [num for num in numbers if num > 10 and is_prime(num)]

print(filtered_numbers)
# 输出 [11, 13, 17, 19]
  • 12
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AnFany

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值