程序员必备的Python技巧和窍门?

在本文中,我们将介绍一些有用的python技巧和窍门,当您在竞争性编程中编写程序时或在您的公司中使用它们时,它们将减少代码并优化执行,因此非常有用。

就地交换两个数字

x, y = 50, 70
print(x, y)

#swapping
x, y = y, x
print(x, y)

输出结果

50 70
70 50

从列表创建单个字符串

lst = ['What', 'a', 'fine', 'morning']
print(" ".join(lst))

输出结果

What a fine morning

从列表中删除重复项

# Remove duplicates from a list

#This method will not preserve the order
lst = [2, 4, 4 ,9 , 13, 4, 2]
print("Original list: ", lst)
new_lst = list(set(lst))
print(new_lst)

# Below method will preserve the order
from collections import OrderedDict
lst = [2, 4, 4 ,9 , 13, 4, 2]
print(list(OrderedDict.fromkeys(lst).keys()))

输出结果

Original list: [2, 4, 4, 9, 13, 4, 2]
[9, 2, 4, 13]
[2, 4, 9, 13]

反转字符串

#Reverse a string
s = "Hello, World!"
print(s[::-1])

letters = ("abcdefghijklmnopqrstuvwxyz")
print(letters[::-1])

输出结果

!dlroW ,olleH
Zyxwvutsrqponmlkjihgfedcba

倒转列表

# Reversing a list

lst = [20, 40 , 60, 80]
print(lst[::-1])

输出结果

[80, 60, 40, 20]

转置二维数组

#Transpose of a 2d array, that means if the matrix is 2 * 3 after transpose it will be 3* 2 matrix.

matrix = [['a', 'b', 'c'], ['d', 'e', 'f']]
transMatrix = zip (*matrix)
print(list (transMatrix))

输出结果

[('a', 'd'), ('b', 'e'), ('c', 'f')]

检查两个字符串是否是字谜

#Check if two strings are anagrams

from collections import Counter

def is_anagram (str1, str2):
return Counter(str1) == Counter(str2)

print(is_anagram('hello', 'ollhe'))
#and
print(is_anagram('Hello', 'hello'))

输出结果

True
False

在python中检查对象

#Inspect an object in pyton

lst =[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', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

列举列表

#Enumerate a list
lst = [20, 10, 40, 50 , 30, 40]
for i, value in enumerate(lst):
print(i, ': ', value)

输出结果

0 : 20
1 : 10
2 : 40
3 : 50
4 : 30
5 : 40

任何数量的阶乘

#Factorial of any number

import functools

result = (lambda s: functools.reduce(int. __mul__, range(1, s+1), 1))(5)
print(result)

输出结果

120

根据两个相关序列创建字典

#Creating a dictionary from two related sequences
x1 = ('Name', 'EmpId', 'Sector')
y1 = ('Zack', 4005, 'Finance')
print(dict (zip(x1, y1)))

输出结果

{'Name': 'Zack', 'EmpId': 4005, 'Sector': 'Finance'}