今天和大家来分享几个关于Python的小技巧,都是非常简单易懂的内容,希望大家看了之后能够有所收获。
my_string = "ABCDE"reversed_string = my_string[::-1]print(reversed_string)--------------------------------------
my_string = "my name is xiao ming"new_string = my_string.title()print(new_string)-------------------------------------
my_string = "aabbbbbccccddddeeeff"temp_set = set(my_string)new_string = ''.join(temp_set)print(new_string)--------------------------------
Python split()通过指定分隔符对字符串进行切片,默认的分隔符是" "
string_1 = "My name is xiao ming"string_2 = "sample, string 1, string 2"
print(string_1.split())
print(string_2.split(','))------------------------------------
list_of_strings = ['My', 'name', 'is', 'Xiao', 'Ming']
print(' '.join(list_of_strings))-----------------------------------------
from collections import Counter
my_list = ['a','a','b','b','b','c','d','d','d','d','d']count = Counter(my_list) print(count)
print(count['b'])
print(count.most_common(1))
dict_1 = {'apple': 9, 'banana': 6}dict_2 = {'grape': 4, 'orange': 8}combined_dict = {**dict_1, **dict_2}print(combined_dict)dict_1.update(dict_2)print(dict_1)print(dict(dict_1.items() | dict_2.items()))---------------------------------------
import time
start_time = time.time()end_time = time.time()time_taken_in_micro = (end_time- start_time) * (10 ** 6)print(time_taken_in_micro)
from iteration_utilities import deepflattenl = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
print(list(deepflatten(l, depth=3)))-----------------------------------------
def unique(l): if len(l)==len(set(l)): print("不存在重复值") else: print("存在重复值")
unique([1,2,3,4])
unique([1,1,2,3])
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]transposed = zip(*array)print(list(transposed)) ------------------------------------------
def difference(a, b): set_a = set(a) set_b = set(b) comparison = set_a.difference(set_b) return list(comparison)
difference([1,2,6], [1,2,5])
def to_dictionary(keys, values): return dict(zip(keys, values)) keys = ["a", "b", "c"] values = [2, 3, 4]print(to_dictionary(keys, values))-------------------------------------------
d = {'apple': 9, 'grape': 4, 'banana': 6, 'orange': 8}sorted(d.items(), key = lambda x: x[1]) sorted(d.items(), key = lambda x: x[1], reverse = True) from operator import itemgetterprint(sorted(d.items(), key = itemgetter(1)))
list1 = [20, 30, 50, 70, 90]
def max_index(list_test): return max(range(len(list_test)), key = list_test.__getitem__)
def min_index(list_test): return min(range(len(list_test)), key = list_test.__getitem__)
max_index(list1)min_index(list1)