公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

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

image.png

技巧 #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>>> x1>>> y2>>> z3

技巧 #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 pb qc rd s

技巧 #6

仅用一行代码实现两个变量的交换

a=7>>> b=5>>> b, a =a, b>>> a5>>> b7

技巧 #7

不使用循环,输出 "codecodecodecode mentormentormentormentormentor"

print "code"4+' '+"mentor"5codecodecodecode 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 Counterdef 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]

分享到:
标签:Python
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定