菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
1482
1

10 个 Python 初学者必知编码小技巧

原创
05/13 14:22
阅读数 2825

file

技巧 #1

字符串翻转

>>> a =  "codementor"
>>> print "Reverse is",a[::-1]
翻转后的结果为 rotnemedoc

技巧 #2

矩阵转置

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

技巧 #3

a = [1,2,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']

编写 Python 代码,实现下面的输出

  • 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]]

不使用循环,将其转变成单个列表

输出:- [1, 2, 3, 4, 5, 6]

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

技巧 #9

检查一个单词和另一个单词是否只是字母顺序不同

def is_anagram(word1, word2):
    """检查一个单词和另一个单词是否只是字母顺序不同
    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.

从字符串输入中获取值

对于输入数据 1 2 3 4 我们希望得到列表 [1, 2, 3, 4]

请注意,列表中的元素都是 int 类型,且只能使用一行代码。

>>> result = map(lambda x:int(x) ,raw_input().split())
1 2 3 4
>>> result
[1, 2, 3, 4]

原文地址:https://www.codementor.io/sumit12dec/pyt...

译文地址:https://lmonkey.com/python/t/22992/10-py...

发表评论

0/200
1482 点赞
1 评论
收藏
为你推荐 换一批