Python Snippets

正念:更清晰地感知所处的环境

今天分享一些python的代码片段,可以用于日常的工作之中,Let's Go!

Merge two dictionaries

Python 3.5 之后,合并多个字典变得更加容易。 可以使用 (**) 运算符在一行中合并多个字典。

  • How
dictionary1 = {"name": "Joy", "age": 25}
dictionary2 = {"name": "Joy", "city": "New York"}

merged_dict = {**dictionary1, **dictionary2}

print("Merged dictionary:", merged_dict)
  • Output

Merged dictionary: {'name': 'Joy', 'age': 25, 'city': 'New York'}

Checking if a File Exists

from os import path

def check_for_file():
    print("Does file exist:", path.exists("data.csv"))

Find Element with Most Occurance

查找列表中出现频率最高的元素

  • How
def most_frequent(list):
  return max(set(list), key=list.count)

mylist = [1,1,2,3,4,5,6,6,2,2]
print("most frequent item is:", most_frequent(mylist))
  • Output

most frequent item is: 2

Convert Two Lists into a Dictionary

日常工作中经常会碰到判断文件是否存在

def list_to_dictionary(keys, values):
  return dict(zip(keys, values))

list1 = [1, 2, 3]
list2 = ['one', 'two', 'three']

print(list_to_dictionary(list1, list2))

Anagrams

同序异构词,指由相同字母构成的单词,但字母顺序不同

from collections import Counter

def is_anagram(string1, string2):
  return Counter(string1) == Counter(string2)

print(is_anagram('race', 'care'))

Memory Usage of Variable

  • How
import sys

var1 = 15
list1 = [1,2,3,4,5]

print(sys.getsizeof(var1), sys.getsizeof(list1))
  • Output:

28 104

End

保持好奇心,Have a nice day!

你可能感兴趣的:(Python Snippets)