ในบทความนี้ เราจะพูดถึงกลเม็ดและเคล็ดลับที่เป็นประโยชน์ของ python ซึ่งจะเป็นประโยชน์เมื่อคุณเขียนโปรแกรมในการเขียนโปรแกรมเชิงแข่งขัน หรือสำหรับบริษัทของคุณ เนื่องจากลดโค้ดและการดำเนินการให้เหมาะสม .
การสลับแทนที่ของตัวเลขสองตัว
x, y =50, 70print(x, y)#swappingx, y =y, xprint(x, y)
ผลลัพธ์
50 7070 50
การสร้างสตริงเดียวจากรายการ
lst =['What', 'a', 'fine', 'morning']print(" ".join(lst)) ผลลัพธ์
เป็นเช้าที่ดีจริงๆ
ลบรายการที่ซ้ำกันออกจากรายการ
# ลบรายการที่ซ้ำกันออกจากรายการ#วิธีนี้จะไม่รักษา orderlst =[2, 4, 4,9, 13, 4, 2]print("Original list:", lst)new_lst =list(set(lst) )) พิมพ์ (new_lst) # วิธีการด้านล่างจะรักษา orderfrom คอลเลกชันนำเข้า OrderedDictlst =[2, 4, 4 ,9 , 13, 4, 2]print(list(OrderedDict.fromkeys(lst).keys()))ก่อน> ผลลัพธ์
รายการเดิม:[2, 4, 4, 9, 13, 4, 2][9, 2, 4, 13][2, 4, 9, 13]
ย้อนกลับสตริง
#Reverse a strings ="สวัสดี ชาวโลก!"print(s[::-1])letters =("abcdefghijklmnopqrstuvwxyz")print(letters[::-1]) ผลลัพธ์
!dlroW ,olleHZyxwvutsrqponmlkjihgfedcba
การกลับรายการ
# การกลับรายการ =[20, 40, 60, 80]print(lst[::-1])
ผลลัพธ์
[80, 60, 40, 20]
เปลี่ยนอาร์เรย์สองมิติ
#Transpose ของอาร์เรย์ 2d หมายความว่าถ้าเมทริกซ์เป็น 2 * 3 หลังจากย้าย มันจะเป็น 3* 2 matrix.matrix =[['a', 'b', 'c'], ['d' , 'e', 'f']]transMatrix =zip (*matrix)print(list (transMatrix))
ผลลัพธ์
[('a', 'd'), ('b', 'e'), ('c', 'f')] ตรวจสอบว่าสองสตริงเป็นแอนนาแกรมหรือไม่
#Check ถ้าสองสตริงเป็นแอนนาแกรมจากคอลเลกชันที่นำเข้า Counterdef is_anagram (str1, str2):return Counter(str1) ==Counter(str2)print(is_anagram('hello', 'ollhe'))#andprint(is_anagram(' สวัสดี', 'สวัสดี')) ผลลัพธ์
TrueFalse
ตรวจสอบวัตถุในหลาม
#ตรวจสอบวัตถุใน pytonlst =[1, 3, 4, 7, 9]print(dir(lst))
เอาท์พุต
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__ '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook'__', 'append ', 'คัดลอก', 'นับ', 'ขยาย', 'ดัชนี', 'แทรก', 'ป๊อป', 'ลบ', 'ย้อนกลับ', 'จัดเรียง']
ระบุรายการ
#Enumerate a listlst =[20, 10, 40, 50 , 30, 40]for i, value in enumerate(lst):print(i, ':', value)
ผลลัพธ์
0 :201 :102 :403 :504 :305 :40
แฟกทอเรียลของจำนวนใดๆ
#แฟกทอเรียลของการนำเข้าตัวเลขใดๆ functoolsresult =(lambda s:functools.reduce(int. __mul__, range(1, s+1), 1))(5)print(result)
ผลลัพธ์
120
การสร้างพจนานุกรมจากสองลำดับที่เกี่ยวข้อง
#การสร้างพจนานุกรมจากสองลำดับที่เกี่ยวข้องx1 =('Name', 'EmpId', 'Sector')y1 =('Zack', 4005, 'Finance')print(dict (zip(x1, y1))) ผลลัพธ์
{'Name':'Zack', 'EmpId':4005, 'Sector':'Finance'}