PythonIt is a powerful interpreted programming language.我們可以通過下面的10optimization techniques to reduce the amount of code and improve the efficiency of the code.
問題:輸出1The square of each number within ten thousand. Found that using list comprehensions takes less time.
from timeit import default_timer as timer
start = timer()
square =[]
for n in range(10000):
square.append(pow(n,2))
end = timer()
print("優化前耗時:",end - start)
#優化後
start2=timer()
square=[pow(n,2) for n in range(10000)]
end2=timer()
print("優化後耗時:",end2 - start2)
print(square)
如果對1Sum the squares of each number within ten thousand,換用PythonGenerator to store process data,We found that it takes up less memory.
import sys
square = [n**2 for n in range(10000)]
print(sum(square))
print(sys.getsizeof(square),'字節') #優化後
square = (n\*\*2 for n in range(10000))
print(sum(square))
print(sys.getsizeof(square),'字節')
lst=[20, 40, 20, 20, 40, 60, 70]
print(sorted(list(lst),reverse=True))
lst=[20, 40, 20, 20, 40, 60, 70]
# print(sorted(list(lst),reverse=True))
print(set(lst))
dogs = ['Harley', 'Phantom', 'Lucky', 'Dingo']
count = 1
for name in dogs:
print(count, name)
count += 1
#優化後
print('優化後')
for i,name in enumerate(dogs,start=1):
print(i,name)
roman_nums = {'I':1, 'II':2, 'III':3, 'IV':4 }
# value=roman_nums['V'] # An error will be reported when accessing a non-existing key value KeyError: 'V'
value=roman_nums.get('V',5)
print('value=',value)
print(roman_nums)
value = roman_nums.setdefault('V',5)
print(roman_nums)
#統計出現次數最多的元素
#This method is introduced first
from collections import Counter
s='hello'
print(Counter(s))
#法二
print([(x,s.count(x)) for x in set(s)])
name,major = "world","computer science"
s="Hello, %s. I major in %s." % (name,major)
s1="Hello, {}. I major in {}.".format(name, major)
s2=f"Hello, {name}. I major in {major}." #推薦用法
print(s,s1,s2,sep='\n')
s=['H','e','l','l','o']
s1=''
for x in s:
s1+=x
print(s1)
s1=''.join(s)#推薦用法
print(s1)
#法一
x = {'a': 1, 'b': 2}
y = {'b': 10, 'c': 11}
x.update(y)
print(x)
#法二 Python3.9+
z = x | y
print(z)
#法三 Python3.5+
z = {**x, **y}
print(z)
#法四
z = dict(list(x.items()) + list(y.items()))
print(z)
如果喜歡,不忘了在微信文章的下面一鍵三連(分享,點贊和收藏).關注微信公眾號“樂享Python”.