素材牛VIP会员
python技巧征集贴
 陈***丶  分类:Python  人气:957  回帖:8  发布于6年前 收藏

Python是十分优美的~~

我想收集些Python语言的技巧。

我先来:

unzip函数的实现 :

zip(*a)
12.03追加

我再追加一个

>>> a=[[1,2,3],[4,5,6],[7,8,9]]
>>> sum(sum(a,[]))
45
 标签:python

讨论这个帖子(8)垃圾回帖将一律封号处理……

Lv4 码徒
ji***ca JS工程师 6年前#1

我再加一个。嘻嘻

Python中链表去重复的快速的方式:

{}.fromkeys(mylist,0).keys()
Lv2 入门
he***ba JS工程师 6年前#2

我在这里写一下Python中的单例模式

class Singleton(object):
  """Singleton pattern
  Somehow singleton in python is useless
  class A:
    class_var = object()
  A() == A() ==> True
  """
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(
                                cls, *args, **kwargs)
        return cls._instance
Lv6 码匠
奇***士 移动开发工程师 6年前#3

我来推荐一个比较新的第三方库 python-sh, 不知是否离题; 如果离题还烦请删除此条答案 :)

from sh import cat, ifconfig, git
content = cat("somefile").stdout
print(ifconfig("wlan0"))
git.checkout("master")

详情请见文档 http://amoffat.github.com/sh/

Lv5 码农
伴***4 JAVA开发工程师 6年前#4
int_list = [1, 2, 3, 4]

if 2 in int_list:
   print "fatastic!"
import traceback
def asdf():
    (filename,line_number,function_name,text)=traceback.extract_stack()[-1]
    print function_name
asdf()

再加一个纯python的模块pexpect吧,这个东西挺好的。

#!/usr/bin/python

import sys
import pexpect

password = 'password'
expect_list = ['(yes/no)', 'password:']

p = pexpect.spawn('ssh username@localhost ls')
try:
    while True:
        idx = p.expect(expect_list)
        print p.before + expect_list[idx],
        if idx == 0:
            print "enter yes"
            p.sendline('yes')
        elif idx == 1:
            print "enter password"
            p.sendline(password)
except pexpect.TIMEOUT:
    print >>sys.stderr, 'timeout'
except pexpect.EOF:
    print p.before
Lv6 码匠
wu***he CEO 6年前#5

PyPy里有一个非常奇特的multimethod库。它的实现 它的测试
有了这个库,就不用写visitor pattern了。你可以写出这样的代码:

from rpython.tool.pairtype import pairtype, pair

class CodeGen(object): pass
class JavaCodeGen(CodeGen): pass
class LispCodeGen(CodeGen): pass
class Ast(object): pass

class Identifier(Ast):
    def __init__(self, name):
        self.name = name

class FunctionCall(Ast):
    def __init__(self, func, args):
        self.func = func
        self.args = args

class __extend__(pairtype(CodeGen, Identifier)):
    def gen((cg, ident)):
        return ident.name

class __extend__(pairtype(JavaCodeGen, FunctionCall)):
    def gen((cg, funcall)):
        funcrepr = pair(cg, funcall.func).gen()
        argreprs = ', '.join(pair(cg, arg).gen() for arg in funcall.args)
        return '%s(%s)' % (funcrepr, argreprs)

class __extend__(pairtype(LispCodeGen, FunctionCall)):
    def gen((cg, funcall)):
        listitems = [funcall.func] + funcall.args
        listrepr = ' '.join(pair(cg, arg).gen() for arg in listitems)
        return '(%s)' % listrepr

# Test
someast = FunctionCall(Identifier('f'),
                       [Identifier('x'),
                        FunctionCall(Identifier('g'),
                                     [Identifier('x')])])

assert pair(JavaCodeGen(), someast).gen() == 'f(x, g(x))'
assert pair(LispCodeGen(), someast).gen() == '(f x (g x))'
Lv6 码匠
风***呀 Web前端工程师 6年前#6

这个问题不好答啊…自己觉得好的技巧,其他人可能非常常用…加上python本来就对问题解法相对单一…

三目运算符
a = True if k in l else False

List Comprehension
a = [ x for x in l if x > 0]

property decorator

class A:
    def __init__(self, name=None):
        self._name = name
    @property
    def name(self):
        return str(len(self._name)) + self._name

a = A("test")
print(a.name)

再补充一个从2.4到3.3都支持的exception捕捉方法,看有没有人需要,灵感来自@felix21的例子

import sys
try:
    ...
except Exception:
    t, e = sys.exc_info()[:2]
    print(e)
Lv5 码农
ju***ou CEO 6年前#7

zip函数都很少用到,所以我是个菜鸟。

Lv3 码奴
wa***88 产品经理 6年前#8

Unpacking

a = 1
b = 2
a, b = b, a

a = 2
b = 1

f = (3, 5)
c, d = f

c = 3
d = 5

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取