正念:更清晰地感知所處的環(huán)境
今天分享一些python的代碼片段,可以用于日常的工作之中官辈,Let's Go!
Merge two dictionaries
在 Python 3.5
之后,合并多個(gè)字典變得更加容易女器。 可以使用 (**) 運(yùn)算符在一行中合并多個(gè)字典刻撒。
- 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
查找列表中出現(xiàn)頻率最高的元素
- 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
日常工作中經(jīng)常會(huì)碰到判斷文件是否存在
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
同序異構(gòu)詞,指由相同字母構(gòu)成的單詞埠通,但字母順序不同
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!