30个python常用技巧

目录
1.原地调换数字

 

 1 python提供了一个直观的方法,去用一行代码解决变量交换问题.请看如下示例:
 2 
 3 x, y = 10, 20
 4 print(x, y)
 5  
 6 x, y = y, x
 7 print(x, y)
 8  
 9 
10 
11 #1 (10, 20)
12 #2 (20, 10)
13 
14 
15 
16 The assignment on the right seeds a new tuple. While the left one instantly unpacks that (unreferenced) tuple to the names <a> and <b>.Once the assignment is through, the new tuple gets unreferenced and flagged for garbage collection. The swapping of variables also occurs at eventually.
17 右边的作业是一个新的元组,左边的作业立刻拆解得到a,b的值,新任务完成,右边的新的元组随之进入系统回收.这样值的交换就实现了
乾坤大挪移

2.比较运算符的连接

 1 Aggregation of comparison operators is another trick that can come handy at times.
 2 
 3 n = 10
 4 result = 1 < n < 20
 5 print(result)
 6 
 7 # True
 8 
 9 result = 1 > n <= 9
10 print(result)
11 
12 # False
比较运算的连接

3.使用三元运算给条件赋值

 1 Ternary operators are a shortcut for an if-else statement and also known as conditional operators.
 2 
 3 [on_true] if [expression] else [on_false]
 4 Here are a few examples which you can use to make your code compact and concise.
 5 
 6 The below statement is doing the same what it is meant to i.e. “assign 10 to x if y is 9, otherwise assign 20 to x“. We can though extend the chaining of operators if required.
 7 
 8 x = 10 if (y == 9) else 20
 9 Likewise, we can do the same for class objects.
10 
11 x = (classA if y == 1 else classB)(param1, param2)
12 In the above example, classA and classB are two classes and one of the class constructors would get called.
13 
14 
15  
16 Below is one more example with a no. of conditions joining to evaluate the smallest number.
17 
18 def small(a, b, c):
19     return a if a <= b and a <= c else (b if b <= a and b <= c else c)
20     
21 print(small(1, 0, 1))
22 print(small(1, 2, 2))
23 print(small(2, 2, 3))
24 print(small(5, 4, 3))
25 
26 #Output
27 #0 #1 #2 #3
28 We can even use a ternary operator with the list comprehension.
29 
30 [m**2 if m > 10 else m**4 for m in range(50)]
31 
32 #=> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
三元合一

4.使用多行字符串

The basic approach is to use backslashes which derive itself from C language.

multiStr = "select * from multi_row \
where row_id < 5"
print(multiStr)

# select * from multi_row where row_id < 5
One more trick is to use the triple-quotes.

multiStr = """select * from multi_row 
where row_id < 5"""
print(multiStr)

#select * from multi_row 
#where row_id < 5
The common issue with the above methods is the lack of proper indentation. If we try to indent, it’ll insert whitespaces in the string.

So the final solution is to split the string into multi lines and enclose the entire string in parenthesis.

multiStr= ("select * from multi_row "
"where row_id < 5 "
"order by age") 
print(multiStr)

#select * from multi_row where row_id < 5 order by age
字符串的拼接

5.将列表元素储存到新的变量中

We can use a list to initialize a no. of variables. While unpacking the list, the count of variables shouldn’t exceed the no. of elements in the list.

testList = [1,2,3]
x, y, z = testList

print(x, y, z)

#-> 1 2 3
吸星大法

6.用模块打印文件地址

 1 If you want to know the absolute location of modules imported in your code, then use the below trick.
 2 
 3 import threading 
 4 import socket
 5 
 6 print(threading)
 7 print(socket)
 8 
 9 #1- <module 'threading' from '/usr/lib/python2.7/threading.py'>
10 #2- <module 'socket' from '/usr/lib/python2.7/socket.py'>
仙人指路

7.使用“_”进行交互.

It’s a useful feature which not many of us are aware.

In the Python console, whenever we test an expression or call a function, the result dispatches to a temporary name, _ (an underscore).

>>> 2 + 1
3
>>> _
3
>>> print _
3
The “_” references to the output of the last executed expression.
帽子戏法

8.字典或集合的一些领悟

Like we use list comprehensions, we can also use dictionary/set comprehensions. They are simple to use and just as effective. Here is an example.

testDict = {i: i * i for i in xrange(10)} 
testSet = {i * 2 for i in xrange(10)}

print(testSet)
print(testDict)

#set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
Note- There is only a difference of <:> in the two statements. Also, to run the above code in Python3, replace <xrange> with <range>.
类似于列表推导式

9.调试脚本

We can set breakpoints in our Python script with the help of the <pdb> module. Please follow the below example.

import pdb
pdb.set_trace()
We can specify <pdb.set_trace()> anywhere in the script and set a breakpoint there. It’s extremely convenient.
断点语句pdb

10.设置文件共享

Python allows running an HTTP server which you can use to share files from the server root directory. Below are the commands to start the server.

# Python 2

python -m SimpleHTTPServer
# Python 3

python3 -m http.server
Above commands would start a server on the default port i.e. 8000. You can also use a custom port by passing it as the last argument to the above commands.
共享单车

11.在python中检查对象

We can inspect objects in Python by calling the dir() method. Here is a simple example.

test = [1, 3, 5, 7]
print( dir(test) )
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
查户口

12.简化if语句

To verify multiple values, we can do in the following manner.

if m in [1,3,5,7]:
instead of:

if m==1 or m==3 or m==5 or m==7:
Alternatively, we can use ‘{1,3,5,7}’ instead of ‘[1,3,5,7]’ forin’ operator because ‘set’ can access each element by O(1).
if技巧

13.python版本检测

Sometimes we may not want to execute our program if the Python engine currently running is less than the supported version. To achieve this, you can use the below coding snippet. It also prints the currently used Python version in a readable format.

import sys

#Detect the Python version currently in use.
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
    print("Sorry, you aren't running on Python 3.5\n")
    print("Please upgrade to 3.5.\n")
    sys.exit(1)
    
#Print Python version in a readable format.
print("Current Python version: ", sys.version)
Alternatively, you can usesys.version_info >= (3, 5) to replacesys.hexversion!= 50660080 in the above code. It was a suggestion from one of the informed reader.

Output when running on Python 2.7.

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
   
Sorry, you aren't running on Python 3.5

Please upgrade to 3.5.
Output when running on Python 3.5.

Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
   
Current Python version:  3.5.2 (default, Aug 22 2016, 21:11:05) 
[GCC 5.3.0]
检测版本

14.拼接字符串

If you want to concatenate all the tokens available in a list, then see the below example.

>>> test = ['I', 'Like', 'Python', 'automation']
Now, let’s create a single string from the elements in the list given above.

>>> print ''.join(test)
列表转化为字符串

15.四个方法反转string/list.

# Reverse The List Itself.

testList = [1, 3, 5]
testList.reverse()
print(testList)

#-> [5, 3, 1]
# Reverse While Iterating In A Loop.

for element in reversed([1,3,5]): print(element)

#1-> 5
#2-> 3
#3-> 1



# Reverse A String In Line.

"Test Python"[::-1]
This gives the output as ”nohtyP tseT”



# Reverse A List Using Slicing.

[1, 3, 5][::-1]
The above command will give the output as [5, 3, 1].
四种反转方式

16.玩枚举

With enumerators, it’s easy to find an index while you’re inside a loop.

testlist = [10, 20, 30]
for i, value in enumerate(testlist):
    print(i, ': ', value)

#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30
枚举的作用

17.在python中使用枚举

With enumerators, it’s easy to find an index while you’re inside a loop.

testlist = [10, 20, 30]
for i, value in enumerate(testlist):
    print(i, ': ', value)

#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30
在python中使用枚举

18.从函数中返回多个值

Not many programming languages support this feature. However, functions in Python do return multiple values.

Please refer the below example to see it working.

# function returning multiple values.
def x():
    return 1, 2, 3, 4

# Calling the above function.
a, b, c, d = x()

print(a, b, c, d)

#-> 1 2 3 4
函数返回多个值

19.Unpack function arguments using splat operator.

The splat operator offers an artistic way to unpack arguments lists. Please refer the below example for clarity.

def test(x, y, z):
    print(x, y, z)

testDict = {'x': 1, 'y': 2, 'z': 3} 
testList = [10, 20, 30]

test(*testDict)
test(**testDict)
test(*testList)

#1-> x y z
#2-> 1 2 3
#3-> 10 20 30
*号打散

20.使用字典储存函数

We can make a dictionary store expressions.

stdcalc = {
    'sum': lambda x, y: x + y,
    'subtract': lambda x, y: x - y
}

print(stdcalc['sum'](9,3))
print(stdcalc['subtract'](9,3))

#1-> 12
#2-> 6
金屋藏娇

21.一行代码实现阶乘

Python 2.X.

result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6
Python 3.X.

import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)
print(result)

#-> 6
阶乘一指

22.找出列表中出现最多的值

test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count))

#-> 4
老常客

23.重置递归限制

Python restricts recursion limit to 1000. We can though reset its value.

import sys

x=1001
print(sys.getrecursionlimit())

sys.setrecursionlimit(x)
print(sys.getrecursionlimit())

#1-> 1000
#2-> 1001
Please apply the above trick only if you need it.
重置递归深度

24.检查对象的内存使用情况

In Python 2.7, a 32-bit integer consumes 24-bytes whereas it utilizes 28-bytes in Python 3.5. To verify the memory usage, we can call the <getsizeof> method.

In Python 2.7.

import sys
x=1
print(sys.getsizeof(x))

#-> 24
In Python 3.5.

import sys
x=1
print(sys.getsizeof(x))

#-> 28
查询内存使用情况

25.使用 __slots__ 节省内存.

Have you ever observed your Python application consuming a lot of resources especially memory? Here is one trick which uses <__slots__> class variable to reduce memory overhead to some extent.

import sys
class FileSystem(object):

    def __init__(self, files, folders, devices):
        self.files = files
        self.folders = folders
        self.devices = devices

print(sys.getsizeof( FileSystem ))

class FileSystem1(object):

    __slots__ = ['files', 'folders', 'devices']
    
    def __init__(self, files, folders, devices):
        self.files = files
        self.folders = folders
        self.devices = devices

print(sys.getsizeof( FileSystem1 ))

#In Python 3.5
#1-> 1016
#2-> 888
Clearly, you can see from the results that there are savings in memory usage. But you should use __slots__ when the memory overhead of a class is unnecessarily large. Do it only after profiling the application. Otherwise, you’ll make the code difficult to change and with no real benefit.
减少内存

26.Lambda to imitate print function.

import sys
lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))
lprint("python", "tips",1000,1001)

#-> python tips 1000 1001
模仿打印

27.Create a dictionary from two related sequences.

t1 = (1, 2, 3)
t2 = (10, 20, 30)

print(dict (zip(t1,t2)))

#-> {1: 10, 2: 20, 3: 30}
创建字典有用!!

28.在字符串中寻找多个前缀

print("http://www.google.com".startswith(("http://", "https://")))
print("http://www.google.co.uk".endswith((".com", ".co.uk")))

#1-> True
#2-> True
找到前缀,后缀

29.不用循环创造一个列表

import itertools
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))

#-> [-1, -2, 30, 40, 25, 35]
If you have an input list with nested lists or tuples as elements, then use the below trick. However, the limitation here is that it’s using a for Loop.

def unifylist(l_input, l_target):
    for it in l_input:
        if isinstance(it, list):
            unifylist(it, l_target)
        elif isinstance(it, tuple):
            unifylist(list(it), l_target)
        else:
            l_target.append(it)
    return l_target

test =  [[-1, -2], [1,2,3, [4,(5,[6,7])]], (30, 40), [25, 35]]

print(unifylist(test,[]))

#Output => [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
Another simpler method to unify the list containing lists and tuples is by using the Python’s <more_itertools> package. It doesn’t require looping. Just do a <pip install more_itertools>, if not already have it.

import more_itertools

test = [[-1, -2], [1, 2, 3, [4, (5, [6, 7])]], (30, 40), [25, 35]]

print(list(more_itertools.collapse(test)))

#Output=> [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
一统江山

30.在python中实现一个真正的开关盒

 

Here is the code that uses a dictionary to imitate a switch-case construct.

def xswitch(x): 
    return xswitch._system_dict.get(x, None) 

xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2}

print(xswitch('default'))
print(xswitch('devices'))

#1-> None
#2-> 2
实现开关盒子

 

转载于:https://www.cnblogs.com/cangshuchirou/p/8678197.html

在使用Python来安装geopandas包时,由于geopandas依赖于几个其他的Python库(如GDAL, Fiona, Pyproj, Shapely等),因此安装过程可能需要一些额外的步骤。以下是一个基本的安装指南,适用于大多数用户: 使用pip安装 确保Python和pip已安装: 首先,确保你的计算机上已安装了Python和pip。pip是Python的包管理工具,用于安装和管理Python包。 安装依赖库: 由于geopandas依赖于GDAL, Fiona, Pyproj, Shapely等库,你可能需要先安装这些库。通常,你可以通过pip直接安装这些库,但有时候可能需要从其他源下载预编译的二进制包(wheel文件),特别是GDAL和Fiona,因为它们可能包含一些系统级的依赖。 bash pip install GDAL Fiona Pyproj Shapely 注意:在某些系统上,直接使用pip安装GDAL和Fiona可能会遇到问题,因为它们需要编译一些C/C++代码。如果遇到问题,你可以考虑使用conda(一个Python包、依赖和环境管理器)来安装这些库,或者从Unofficial Windows Binaries for Python Extension Packages这样的网站下载预编译的wheel文件。 安装geopandas: 在安装了所有依赖库之后,你可以使用pip来安装geopandas。 bash pip install geopandas 使用conda安装 如果你正在使用conda作为你的Python包管理器,那么安装geopandas和它的依赖可能会更简单一些。 创建一个新的conda环境(可选,但推荐): bash conda create -n geoenv python=3.x anaconda conda activate geoenv 其中3.x是你希望使用的Python版本。 安装geopandas: 使用conda-forge频道来安装geopandas,因为它提供了许多地理空间相关的包。 bash conda install -c conda-forge geopandas 这条命令会自动安装geopandas及其所有依赖。 注意事项 如果你在安装过程中遇到任何问题,比如编译错误或依赖问题,请检查你的Python版本和pip/conda的版本是否是最新的,或者尝试在不同的环境中安装。 某些库(如GDAL)可能需要额外的系统级依赖,如地理空间库(如PROJ和GEOS)。这些依赖可能需要单独安装,具体取决于你的操作系统。 如果你在Windows上遇到问题,并且pip安装失败,尝试从Unofficial Windows Binaries for Python Extension Packages网站下载相应的wheel文件,并使用pip进行安装。 脚本示例 虽然你的问题主要是关于如何安装geopandas,但如果你想要一个Python脚本来重命名文件夹下的文件,在原始名字前面加上字符串"geopandas",以下是一个简单的示例: python import os # 指定文件夹路径 folder_path = 'path/to/your/folder' # 遍历文件夹中的文件 for filename in os.listdir(folder_path): # 构造原始文件路径 old_file_path = os.path.join(folder_path, filename) # 构造新文件名 new_filename = 'geopandas_' + filename # 构造新文件路径 new_file_path = os.path.join(folder_path, new_filename) # 重命名文件 os.rename(old_file_path, new_file_path) print(f'Renamed "{filename}" to "{new_filename}"') 请确保将'path/to/your/folder'替换为你想要重命名文件的实际文件夹路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值