最近看到我关注的某公众号,文章是从网上原封不动的抄的,随便一搜,网络上都是那个文章。这个还不是重点,重点是,代码里有很多错误,而且是用截图方式弄的,别人想借鉴,还不能copy. 我重新整理了一下,并且在自己机器上运行通过,也算是自己巩固,然后正本清源吧!
给定具体的大小,定义一个函数以按照这个大小切割列表。
from math import ceil
def chunk(lst, size):
return list( map(lambda x: lst[x * size:x * size + size], list(range(0, ceil(len(lst) / size)))))
print(chunk([1,2,3,4,5],2))# [[1,2],[3,4],5]
这个方法可以将布尔型的值去掉,例如(False,None,0,“”),它使用 filter() 函数。
def compact(lst):
return list(filter(bool, lst))
print(compact([0, 1, False, 2, '', 3, 'a', 's', 34]))# [ 1, 2, 3, 'a', 's', 34 ]
如下代码段可以将打包好的成对列表解开成两组不同的元组。
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = list(zip(*array))
print(transposed)# [('a', 'c', 'e'), ('b', 'd', 'f')]
print(*transposed) # ('a', 'c', 'e') ('b', 'd', 'f')
下面的代码可以将列`表连接成单个字符串,且每一个元素间的分隔方式设置为了逗号。
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming
该方法将返回第一个列表的元素,其不在第二个列表内。如果同时要反馈第二个列表独有的元素,还需要加一 set_b.difference(set_a).
def difference(a, b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
print(difference([1,2,3], [1,2,4])) # [3]
如下方法首先会应用一个给定的函数,然后再返回应用函数后结果有差别的列表元素。
from math import floor
def difference_by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
print(difference_by([2.1, 1.2], [2.3, 3.4],floor)) # [1.2]
import os
print(os.getcwd())
my_file = [d for d in os.listdir(".")]
print(my_file)
import os
#__file__是当前执行的文件
# 获取当前文件__file__的路径
print("os.path.realpath(__file__)={}".format(os.path.realpath(__file__)))
# 获取当前文件__file__的所在目录
print(os.path.dirname(os.path.realpath(__file__)))
# 获取当前文件__file__的所在目录
print(os.path.split(os.path.realpath(__file__))[0])
for d in os.listdir(os.path.split(os.path.realpath(__file__))[0]):
print(d)
如果需要深层的,则需要递归了,并且判断 isfile(), isdir()
10. 字符串反转
切片操作来反转字符串:
# Reversing a string using slicing
my_string = "ABCDE"
reversed_string = my_string[::-1]
print(reversed_string)
# Output
# EDCBA
my_string = "my name is chaitanya baweja"
# using the title() function of string class
new_string = my_string.title()
print(new_string)
# Output
# My Name Is Chaitanya Baweja
my_string = "aavvccccddddeee"
# converting the string to a set
temp_set = set(my_string)
# stitching set into a string using join
new_string = ''.join(temp_set)
print(new_string)
n = 3 # number of repetitions
my_string = "abcd"
my_list = [1,2,3]
print(my_string*n)
# abcdabcdabcd
print(my_string*n)
# [1,2,3,1,2,3,1,2,3]
列表元素也可以
n = 4
my_list = [0]*n
# [0, 0, 0, 0]
original_list = [1,2,3,4]
new_list = [2*x for x in original_list]
print(new_list)
# [2,4,6,8]
a = 1
b = 2
a, b = b, a
print(a) # 2
print(b) # 1
string_1 = "My name is Chaitanya Baweja"
string_2 = "sample/ string 2"
# 默认分割符 ' '
print(string_1.split())
# ['My', 'name', 'is', 'Chaitanya', 'Baweja']
# 自定义分割符 '/'
print(string_2.split('/'))
# ['sample', ' string 2']
list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
# Using join with the comma separator
print(','.join(list_of_strings))
# Output
# My,name,is,Chaitanya,Baweja
my_string = "abcba"
if my_string == my_string[::-1]:
print("palindrome")
else:
print("not palindrome")
# Output
# palindrome
Counter可以统计给定列表中每个元素的个数,其中 most_common()可以返回列表数量最多的元素
# finding frequency of each element in a list
from collections import Counter
my_list = ['a','a','b','b','b','c','d','d','d','d','d']
count = Counter(my_list) # defining a counter object
print(count) # Of all elements
# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
print(count['b']) # of individual element
# 3
print(count.most_common(1)) # most frequent element
# [('d', 5)]
Counter正好可以用于解决这个问题,因为包含相同元素且元素数量都相同。
示例如下:
from collections import Counter
str_1, str_2, str_3 = "acbde", "abced", "abcda"
cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)
if cnt_1 == cnt_2:
print('1 and 2 anagram')
if cnt_1 == cnt_3:
print('1 and 3 anagram')
此外,如果需要运行是否发现异常的都需要执行的代码,可以采用 finally ,
a, b = 1,0
try:
print(a/b)
# exception raised when b is 0
except ZeroDivisionError:
print("division by zero")
else:
print("no exceptions raised")
finally:
print("Run this always")
my_list = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(my_list):
print('{0}: {1}'.format(index, value))
# 0: a
# 1: b
# 2: c
# 3: d
# 4: e
注意,这里还可以指定索引开始的范围,添加一个参数
my_list = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(my_list, 1):
print('{0}: {1}'.format(index, value))
import sys
num = 21
print(sys.getsizeof(num))
# In Python 2, 24
# In Python 3, 28
dict_1 = {'apple': 9, 'banana': 6}
dict_2 = {'banana': 4, 'orange': 8}
combined_dict = {**dict_1, **dict_2}
print(combined_dict)
# Output
# {'apple': 9, 'banana': 4, 'orange': 8}
import time
start_time = time.time()
# Code to check follows
a, b = 1,2
c = a+ b
# Code to check ends
end_time = time.time()
time_taken_in_micro = (end_time- start_time)*(10**6)
print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)
from iteration_utilities import deepflatten
# 列表只有一层深度的情况,采用这个函数
def flatten(l):
return [item for sublist in l for item in sublist]
l = [[1,2,3],[3]]
print(flatten(l))
# [1, 2, 3, 3]
# 不知道列表的深度的情况
l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
print(list(deepflatten(l, depth=3)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
import random
my_list = ['a', 'b', 'c', 'd', 'e']
num_samples = 2
samples = random.sample(my_list,num_samples)
print(samples)
# [ 'a', 'e'] this will have any 2 random values
另外,在 Python 3 中推荐采用 secrets 模块
import secrets # imports secure module.
secure_random = secrets.SystemRandom() # creates a secure random object.
my_list = ['a','b','c','d','e']
num_samples = 2
samples = secure_random.sample(my_list, num_samples)
print(samples)
# [ 'e', 'd'] this will have any 2 random values
def unique(l):
if len(l)==len(set(l)):
print("All elements are unique")
else:
print("List has duplicates")
unique([1,2,3,4])
# All elements are unique
unique([1,1,2,3])
# List has duplicates
平时自己不断积累,才会有所收获,看到错误也能立即发现。