翼度科技»论坛 编程开发 python 查看内容

13 个非常有用的 Python 代码片段

8

主题

8

帖子

24

积分

新手上路

Rank: 1

积分
24
1:将两个列表合并成一个字典

假设我们在 Python 中有两个列表,我们希望将它们合并为字典形式,其中一个列表的项作为字典的键,另一个作为值。这是在用 Python 编写代码时经常遇到的一个非常常见的问题
但是为了解决这个问题,我们需要考虑几个限制,比如两个列表的大小,两个列表中元素的类型,以及其中是否有重复的元素,尤其是我们将使用的元素作为 key 时。我们可以通过使用 zip 等内置函数来解决这些问题
  1. keys_list = ['A', 'B', 'C']
  2. values_list = ['blue', 'red', 'bold']
  3. #There are 3 ways to convert these two lists into a dictionary
  4. #1- Using Python's zip, dict functionz
  5. dict_method_1 = dict(zip(keys_list, values_list))
  6. #2- Using the zip function with dictionary comprehensions
  7. dict_method_2 = {key:value for key, value in zip(keys_list, values_list)}
  8. #3- Using the zip function with a loop
  9. items_tuples = zip(keys_list, values_list)
  10. dict_method_3 = {}
  11. for key, value in items_tuples:
  12.     if key in dict_method_3:
  13.         pass # To avoid repeating keys.
  14.     else:
  15.         dict_method_3[key] = value
复制代码
2:将两个或多个列表合并为一个包含列表的列表

另一个常见的任务是当我们有两个或更多列表时,我们希望将它们全部收集到一个大列表中,其中较小列表的所有第一项构成较大列表中的第一个列表
例如,如果我们有 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]]
  1. def merge(*args, missing_val = None):
  2. #missing_val will be used when one of the smaller lists is shorter tham the others.
  3. #Get the maximum length within the smaller lists.
  4.   max_length = max([len(lst) for lst in args])
  5.   outList = []
  6.   for i in range(max_length):
  7.     result.append([args[k][i] if i < len(args[k]) else missing_val for k in range(len(args))])
  8.   return outList
复制代码
3:对字典列表进行排序

这一组日常列表任务是排序任务,根据列表中包含的元素的数据类型,我们将采用稍微不同的方式对它们进行排序。
  1. dicts_lists = [
  2.   {
  3.     "Name": "James",
  4.     "Age": 20,
  5.   },
  6.   {
  7.      "Name": "May",
  8.      "Age": 14,
  9.   },
  10.   {
  11.     "Name": "Katy",
  12.     "Age": 23,
  13.   }
  14. ]
  15. #There are different ways to sort that list
  16. #1- Using the sort/ sorted function based on the age
  17. dicts_lists.sort(key=lambda item: item.get("Age"))
  18. #2- Using itemgetter module based on name
  19. from operator import itemgetter
  20. f = itemgetter('Name')
  21. dicts_lists.sort(key=f)
复制代码
4:对字符串列表进行排序

我们经常面临包含字符串的列表,我们需要按字母顺序、长度或我们想要或我们的应用程序需要的任何其他因素对这些列表进行排序
  1. my_list = ["blue", "red", "green"]
  2. #1- Using sort or srted directly or with specifc keys
  3. my_list.sort() #sorts alphabetically or in an ascending order for numeric data
  4. my_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest.
  5. # You can use reverse=True to flip the order
  6. #2- Using locale and functools
  7. import locale
  8. from functools import cmp_to_key
  9. my_list = sorted(my_list, key=cmp_to_key(locale.strcoll))
复制代码
5:根据另一个列表对列表进行排序

有时,我们可能需要使用一个列表来对另一个列表进行排序,因此,我们将有一个数字列表(索引)和一个我们想使用这些索引进行排序的列表
  1. a = ['blue', 'green', 'orange', 'purple', 'yellow']
  2. b = [3, 2, 5, 4, 1]
  3. #Use list comprehensions to sort these lists
  4. sortedList =  [val for (_, val) in sorted(zip(b, a), key=lambda x: \
  5.           x[0])]
复制代码
6:将列表映射到字典

列表代码片段的最后一个任务,如果给定一个列表并将其映射到字典中,也就是说,我们想将我们的列表转换为带有数字键的字典
  1. mylist = ['blue', 'orange', 'green']
  2. #Map the list into a dict using the map, zip and dict functions
  3. mapped_dict = dict(zip(itr, map(fn, itr)))
复制代码
现在处理的数据类型是字典
7:合并两个或多个字典

假设我们有两个或多个字典,并且我们希望将它们全部合并为一个具有唯一键的字典
  1. from collections import defaultdict
  2. #merge two or more dicts using the collections module
  3. def merge_dicts(*dicts):
  4.   mdict = defaultdict(list)
  5.   for dict in dicts:
  6.     for key in dict:
  7.       res[key].append(d[key])
  8.   return dict(mdict)
复制代码
8:反转字典

一个非常常见的字典任务是如果我们有一个字典并且想要翻转它的键和值,键将成为值,而值将成为键
当我们这样做时,我们需要确保没有重复的键。值可以重复,但键不能,并确保所有新键都是可以 hashable 的
  1. my_dict = {
  2.   "brand": "Ford",
  3.   "model": "Mustang",
  4.   "year": 1964
  5. }
  6. #Invert the dictionary based on its content
  7. #1- If we know all values are unique.
  8. my_inverted_dict = dict(map(reversed, my_dict.items()))
  9. #2- If non-unique values exist
  10. from collections import defaultdict
  11. my_inverted_dict = defaultdict(list)
  12. {my_inverted_dict[v].append(k) for k, v in my_dict.items()}
  13. #3- If any of the values are not hashable
  14. my_dict = {value: key for key in my_inverted_dict for value in my_inverted_dict[key]}
复制代码
接下来是字符串的处理
9:使用 f 字符串

格式化字符串可能是我们几乎每天都需要完成的一项任务,在 Python 中有多种方法可以格式化字符串,使用 f 字符串是比较好的选择
  1. #Formatting strings with f string.
  2. str_val = 'books'
  3. num_val = 15
  4. print(f'{num_val} {str_val}') # 15 books
  5. print(f'{num_val % 2 = }') # 1
  6. print(f'{str_val!r}') # books
  7. #Dealing with floats
  8. price_val = 5.18362
  9. print(f'{price_val:.2f}') # 5.18
  10. #学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078
  11. #Formatting dates
  12. from datetime import datetime;
  13. date_val = datetime.utcnow()
  14. print(f'{date_val=:%Y-%m-%d}') # date_val=2021-09-24
复制代码
10:检查子串

一项非常常见的任务就是检查字符串是否在与字符串列表中
  1. addresses = ["123 Elm Street", "531 Oak Street", "678 Maple Street"]
  2. street = "Elm Street"
  3. #The top 2 methods to check if street in any of the items in the addresses list
  4. #1- Using the find method
  5. for address in addresses:
  6.     if address.find(street) >= 0:
  7.         print(address)
  8. #2- Using the "in" keyword
  9. for address in addresses:
  10.     if street in address:
  11.         print(address)
复制代码
11:以字节为单位获取字符串的大小

有时,尤其是在构建内存关键应用程序时,我们需要知道我们的字符串使用了多少内存
[code]str1 = "hello"str2 = "
来源:https://www.cnblogs.com/python1111/p/17231135.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具