网站首页 > 技术文章 正文
编程派微信号:codingpy
在昨天分享的《请不要为了炫耀而写出超短代码》一文中,提到了两种短代码:一种是写给自己看的,另一种是写给别人看的。本文再分享一些短代码的示例,有些虽短,但也有可读性;有些就纯粹属于写给自己看的了。
1、让列表中的每个元素都乘以2
print map(lambda x: x * 2, range(1,11))
2、求列表中的所有元素之和
print sum(range(1,1001))
3、判断一个字符串中是否存在某些词
wordlist = ["scala", "akka", "play framework", "sbt", "typesafe"]tweet = "This is an example tweet talking about scala and sbt."
print map(lambda x: x in tweet.split(),wordlist)
4、读取文件
print open("ten_one_liners.py").readlines()
5、祝你生日快乐!
print map(lambda x: "Happy Birthday to " + ("you" if x != 2 else "dear Name"),range(4))
6. 过滤列表中的数值
print reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[]))
7. 获取XML web service数据并分析
from xml.dom.minidom import parse, parseString
import urllib2
# 注意,我将它转换成XML格式化并打印出来
print parse(urllib2.urlopen("http://search.twitter.com/search.atom?&q=python")).toprettyxml(encoding="utf-8")
8. 找到列表中最小或最大的一个数字
print min([14, 35, -7, 46, 98])
print max([14, 35, -7, 46, 98])
9. 并行处理
import multiprocessing
import math
print list(multiprocessing.Pool(processes=4).map(math.exp,range(1,11)))
10. “Sieve of Eratosthenes”算法
Python里没有埃拉托色尼选筛法(Sieve of Eratosthenes)操作符,但这对于Python来说并不是难事。
n = 50 # 求 2-50 之间的素数
print sorted(set(range(2,n+1)).difference(set((p * f) for p in range(2,int(n**0.5
更多Python教程,请关注微信公众号编程派(codingpy)。
猜你喜欢
- 2025-05-11 5 个让代码更干净、更高效的 Python 好习惯
- 2025-05-11 掌握5 个 Python关键程序,编写更清晰、更高效的代码
- 2025-05-11 10个Python单行代码技巧,快速搞定数据清洗
- 2025-05-11 你应该知道的 50 个 Python 单行代码
- 2025-05-11 如何使用 Python 操作 Git 代码?GitPython 入门介绍
- 2025-05-11 一行代码可以做什么?Python给你答案
- 2025-05-11 10 个 Python 单行代码搞定 Scikit-learn 任务,效率提升 80%!
- 2025-05-11 6行Python代码实现进度条效果(tqdm,Progress)
- 2025-05-11 Python进阶-day20: 代码风格与工具
- 2025-05-11 需要知道12 个 Python 单行代码1
- 05-27程序员用 Python 爬取抖音高颜值美女
- 05-27YOLO v3、FaceNet和SVM的人脸检测识别系统源码(python)分享
- 05-27「工具推荐」世界上最简单的人脸识别库 44.7 star
- 05-27开源人脸识别系统源码推荐
- 05-27Go 人脸识别教程
- 05-27Python 深度学习之人脸识别(yolo+facenet)
- 05-27简单的Py人脸识别
- 05-27Python编程 - 基于OpenCV实现人脸识别(实践篇)爬虫+人脸识别
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 82℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)