Giter Site home page Giter Site logo

python's People

Contributors

wangpengqut avatar

Watchers

 avatar

python's Issues

20180210_Python_tips

01 如何去掉list中重复元素

my_list = [3,2,1,1,2,3]
print(my_list)

unique_list = list(set(my_list))
print(unique_list)

#前一种方式不会保留list的元素顺序,后一种方式会保留list的元素顺序
from collections import OrderedDict

my_list = [3,2,1,1,2,3]
print(my_list)

unique_list = list(OrderedDict.fromkeys(my_list))
print(unique_list)print(unique_list)

02 如何读取dict中的值

url_dict = {'google':'https://www.google.com',
'github':'https://github.com',
'facebook':'https://www.facebook.com'}

print(url_dict['facebook'])
print(url_dict['github'])
print(url_dict['google'])

#后一种方式使用字典的get方法,如果key不存在,不会产生KeyError,如果给了默认值,会返回默认值,否则返回None。
url_dict = {'google':'https://www.google.com',
'github':'https://github.com',
'facebook':'https://www.facebook.com'}

print(url_dict.get('facebook','https://www.facebook.com'))
print(url_dict.get('github','https://github.com'))
print(url_dict.get('google','https://www.google.com'))

03 如何排序字典

#第一种方式是按字典的value升序排序,第二种方式是按字典的key升序排序,第三种方式是按字典的value降序排序,
#和第一种方式相反,因为指定了参数reverse为True。sorted函数功能挺强大,不止可以排序字典,任何iterable对象都可以排序。
unordered_dict = {'c':1,'b':2,'a':3}

print(sorted(unordered_dict.items(),key=lambda e: e[1]))

print(sorted(unordered_dict.items(),key=lambda e: e[0]))

print(sorted(unordered_dict.items(),key=lambda e: e[1], reverse=True))

04 如何打印更易读的类

class Point(object):
def init(self,x,y):
self.x = x
self.y = y

p = Point(3,4)
print(p)

#前一种方式打印的类不易读,不能获取更多的信息。通过类的repr方法可以将类打印得更易读。
#或者不定义repr方法,直接使用下面方式打印:
#print p.dict# {'y': 4, 'x': 3}
#使用dict方法,将类以字典形式打印出来,也比较易读。
class Point(object):
def init(self,x,y):
self.x = x
self.y = y

def __repr__(self):
    return 'Point({self.x},{self.y})'.format(self=self)

p = Point(3,4)
print(p)

05 如何将类打印成json字符串

#通过json模块的dumps方法,可以轻易将类打印成json字符串。
import json

class User(object):
def init(self,name,id):
self.name = name
self.id = id

u = User('user1',1)
print(json.(u.dict,indent=4))

#06 如何排序类列表
class User:
def init(self,name,key):
self.name = name
self.key = key

def __repr__(self):
    return 'User({self.name},{self.key})'.format(self=self)

user_list = [User('user1',3),
User('user2',2),
User('user3',1),]

print(sorted(user_list,key=lambda user:user.key))

print(sorted(user_list,key=lambda user:user.name))

#这里排序的方法和字典排序类似,第一种是按user的key升序排序,
#第二种是按user的name升序排序。其实还支持名字相同,再按key进行排序,如下:
user_list = [User('user1',3),
User('user1',2),
User('user2',1),]

print(sorted(user_list,key=lambda user:(user.name, user.key)))

20180211_Python_tips

01 如何在命令行查看python文档

#第一个命令pydoc sys.exit查看sys模块的exit函数文档信息,第二个命令pydoc sorted查看了内建函数sorted的文档信息。
pydoc sys.
Help on built-in function exit in sys:

sys.exit = exit(...)
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e.,success).
If the status is an integer, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure)

pydoc sorted
Help on built-in function sorted in module builtin:

sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) -->

02 如何将python代码打包成独立的二进制文件

#需要编译的python代码如下:

#!/usr/bin/env python# -- coding: utf-8 --print 'hello, world!'

#将python代码打包成独立的二进制文件步骤: 我解释下上面命令行,首先使用python直接运行需要编译成独立二进制文件的hello_world.py,
#程序正常打印hello, world!,然后使用pip安装pyinstaller,通过pyinstaller将hello_world.py打包成独立的二进制文件,
#然后进入当前目录下的dist目录,运行打包成功的二进制文件hello_world,程序正常打印hello, world!。除了pyinstaller,
#还有其他工具可以实现类似功能
python hello_world.py

pip install pyinstaller
pyinstaller -F hello_world.py
cd ./dist/
./hello_world

03 如何自动格式化python代码

#格式化前的demo.py代码:
安装autopep8,并使用autopep8格式化demo.py代码:
pip install autopep8
autopep8 --in-place --aggressive --aggressive demo.py

04 正确的函数返回

#前一种方式中,如果输入的参数b为0,函数会默认返回None,这是一个不太好的编程习惯。
#例如,当把函数的返回值作为if条件判断时,0.0和None都是False,这样容易导致bug。
#后面这种方式,将除数是0当成异常抛出,让调用者处理异常,是比较合理的做法。
def divide(a,b):
try:
return a*1.0/b
except ZeroDivisionError as e:
raise e

print(divide(0,1))

print(divide(1,0))

05 正确使用函数默认参数

def gen_list(a=[],b=None):
a.append(b)
return a

print(gen_list(b=2))

print(gen_list(b=3))
#前一种方式会导致函数默认值改变,多次调用相互影响。正确方式是将函数默认值设置成None,在函数内部初始化默认参数。
#这里只是针对传递引用类型的参数,如果是数字、字符串等类型就不存在该问题。
def gen_list(a=None,b=None):
if a is None:
a=[]
a.append(b)
return a

print(gen_list(b=2))

print(gen_list(b=3))

06 利用元组传递多个函数参数

def demo(a,b,c,d):
print(a,b,c,d)

args = (1,2,3,4)
demo(*args)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.