13 个非常有用的 Python 代码片段,建议收藏!
今天我们主要来介绍应用程序当中的通用 Python 代码片段,一起进步吧。
Lists Snippets
我们先从最常用的数据结构列表开始。
1.将两个列表合并成一个字典
假设我们在 Python 中有两个列表,我们希望将它们合并为字典形式,其中一个列表的项作为字典的键,另一个作为值。这是在用 Python 编写代码时经常遇到的一个非常常见的问题。
但是为了解决这个问题,我们需要考虑几个限制,比如两个列表的大小,两个列表中元素的类型,以及其中是否有重复的元素,尤其是我们将使用的元素作为 key 时。我们可以通过使用 zip 等内置函数来解决这些问题。
keys_list = [A, B, C]
values_list = [blue, red, bold]
#There are 3 ways to convert these two lists into a dictionary
#1- Using Pythons zip, dict functionz
dict_method_1 = dict(zip(keys_list, values_list))
#2- Using the zip function with dictionary comprehensions
dict_method_2 = {key:value for key, value in zip(keys_list, values_list)}
#3- Using the zip function with a loop
items_tuples = zip(keys_list, values_list)
dict_method_3 = {}
for key, value in items_tuples:
if key in dict_method_3:
pass # To avoid repeating keys.
else:
dict_method_3[key] = value2.将两个或多个列表合并为一个包含列表的列表
另一个常见的任务是当我们有两个或更多列表时,我们希望将它们全部收集到一个大列表中,其中较小列表的所有第一项构成较大列表中的第一个列表。
例如,如果我们有 4 个列表 [1,2,3], [a,b,c], [h,e,y] 和 [4,5, 6],我们想为这四个列表创建一个新列表;它将是 [[1,a,h,4], [2,b,e,5], [3,c,y,6]]
def merge(*args, missing_val = None):
#missing_val will be used when one of the smaller lists is shorter tham the others.
#Get the maximum length within the smaller lists.
max_length = max([len(lst) for lst in args])
outList = []
for i in range(max_length):
result.append([args[k][i] if i