Python 10 个最好的特性

翻译自Quora, 读来比较有趣, 文中列举的十个特性基本都算语法糖一类的东西, 从中可以窥见 python 的设计理念. 而且, 很有趣的是, 我发现这些特性, Scala 里也基本都有的~~其他几个答案也不错, 原文见这里: What are the 10 best features of Python?

特性1: 反转字符串

>>> a =  "codementor"
>>> print "Reverse is",a[::-1]
Reverse is rotnemedoc

特性2: 矩阵转置

>>> mat = [[1, 2, 3], [4, 5, 6]]
>>> zip(*mat)
[(1, 4), (2, 5), (3, 6)]

特性3: 将列表中的所有三个值存储在3个新变量中

>>> a = [1, 2, 3]
>>> x, y, z = a 
>>> x
1
>>> y
2
>>> z
3

特性4: 列表转字符串

a = ["Code", "mentor", "Python", "Developer"]
>>> print " ".join(a)
Code mentor Python Developer

特性5: 列表拉链

原文:
List 1 = [‘a’, ‘b’, ‘c’, ‘d’]
List 2 = [‘p’, ‘q’, ‘r’, ‘s’]

Write a Python code to print

ap
bq
cr
ds

>>> for x, y in zip(list1,list2):
...    print x, y
...
a p
b q
c r
d s

特性6: 一行代码交换两个值

>>> a=7
>>> b=5
>>> b, a =a, b
>>> a
5
>>> b
7

特性7: 不使用循环, 打印 ‘codecodecodecode mentormentormentormentormentor’

>>> print "code"*4+' '+"mentor"*5
codecodecodecode mentormentormentormentormentor

特性8: 多重嵌套列表转单一列表

如:
a = [[1, 2], [3, 4], [5, 6]]
转为 Output:- [1, 2, 3, 4, 5, 6]

>>> import itertools 
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

特性9: 检查两个单词是否是相互颠倒的

def is_anagram(word1, word2):
    """Checks whether the words are anagrams.
    word1: string
    word2: string
    returns: boolean
    """

实现:

from collections import Counter
def is_anagram(str1, str2):
     return Counter(str1) == Counter(str2)
>>> is_anagram('abcd','dbca')
True
>>> is_anagram('abcd','dbaa')
False

特性10: 一行代码获取用户输入并放到列表中
input: “1 2 3 4 ”
return [1,2,3,4]

>>> result = map(lambda x:int(x) ,raw_input().split())
1 2 3 4
>>> result
[1, 2, 3, 4]
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值