欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > Python精选200+Tips:1-5

Python精选200+Tips:1-5

2024/10/25 6:32:42 来源:https://blog.csdn.net/qq_32882309/article/details/141723559  浏览:    关键词:Python精选200+Tips:1-5

Pick a flower, You will have a world

  • 001 list
  • 002 set
  • 003 dict
  • 004 tuple
  • 005 str

运行系统: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_listflattened = 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 itemflattened = 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 Falsefor i in range(2, int(n ** 0.5) + 1):if n % i == 0:return Falsereturn Truenumbers = [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]

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com