Python中一些不同的技巧和窍门。这些技巧使你在写Python代码时更加容易和快速,并给你一些好的工具,以便将来使用。你最喜欢的Python技巧和窍门是什么?让我知道吧!
Python是目前最受欢迎的语言之一。它的简洁和高可读性使它在所有的程序员中非常受欢迎。因此,这里有一些技巧和窍门,你可以用来提高你的Python编程游戏。
1.两个变量值互换 In-Place Swapping Of Two Numbers
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
Output:
10 20
20 10
2.反转一个字符串Reversing a string in Python
a = "GeeksForGeeks"
print("Reverse is", a[::-1])
Output:
Reverse is skeeGroFskeeG
3.列表中的所有元素创建一个单一的字符串Create a single string from all the elements in list
a = ["Geeks", "For", "Geeks"]
print(" ".join(a))
Output:
Geeks For Geeks
4.比较运算符的链式运算Chaining Of Comparison Operators.
n = 10
result = 1 < n < 20
print(result)
result = 1 > n <= 9
print(result)
Output:
True
False
5.打印导入的模块的文件路径Print The File Path Of Imported Modules.
import os
import socket
print(os)
print(socket)
Output:
<module 'os' from '/usr/lib/python3.5/os.py'>
<module 'socket' from '/usr/lib/python3.5/socket.py'>
6. Use Of Enums In Python.
class MyName:
Geeks, For, Geeks = range(3)
print(MyName.Geeks)
print(MyName.For)
print(MyName.Geeks)
Output:
2
1
2
6.从函数中返回多个值 Return Multiple Values From Functions.
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
Output:
1 2 3 4
7.在一个列表中寻找最频繁出现的值 Find The Most Frequent Value In A List.
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
Output:
4
8.检查一个对象的内存使用情况 Check The Memory Usage Of An Object.
import sys
x = 1
print(sys.getsizeof(x))
Output:
28
9.打印字符串N次 Print string N times.
n = 2
a = "GeeksforGeeks"
print(a * n)
Output:
GeeksforGeeksGeeksforGeeks
10.检查两个词是否是同音异义词 Checking if two words are anagrams
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
# or without having to import anything
def is_anagram(str1, str2):
return sorted(str1) == sorted(str2)
print(is_anagram('geek', 'eegk'))
print(is_anagram('geek', 'peek'))
Output:
True
False
Python技巧和窍门,这些技巧使它变得有趣和优雅。还有许多其他值得探索的语言特性。