有趣的超短Python代码

本文介绍了使用Python进行的一些基本操作,包括列表元素翻倍、求和、字符串匹配、文件读取等,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-- coding:utf-8 --

python2.7

1让列表的每个元素都乘以2

print map(lambda x: x*2,range(1,11))

2求列表中所有元素之和

print sum(range(1,100)) #range(1,100)代表从1到100(不包含100)

3,判断一个字符串中是否存在某些词

wordlist = [“scala”,”akka”,”play framework”,”sbt”,”typesafe”]
tweet = “This is an example tweet talking about scala an sbt”
print map(lambda x:x in tweet.split(),wordlist)

Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串 这里默认为空格

4,读取文件

print open(“test.txt”).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],([],[]))

结果:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
4950
[True, False, False, True, False]
[‘this is a test\n’, ‘no more words’]
[‘happy birthday toYOU’, ‘happy birthday toYOU’, ‘happy birthday todear Name’, ‘happy birthday toYOU’]
([76, 82, 88, 90], [49, 58])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值