首页 > 编程语言 >python中的列表推导式

python中的列表推导式

时间:2022-12-28 15:38:55浏览次数:63  
标签:推导 python list1 list3 list2 print 列表 append


1.单列表,单条件

求1-20之间的偶数

list1 = []
for i in range(1, 21):
if i % 2 == 0:
list1.append(i)
print(list1)

列表推导式

list2 = [i for i in range(1, 21) if i % 2 == 0]
print(list2)
2.单列表,双条件

有数字1, 2 ,3, 4这些数字 若是奇数,减1 否则加1

list1 = []
list2 = [1, 2, 3, 4]
for i in list2:
if i % 2 == 0:
list1.append(i + 1)
else:
list1.append(i - 1)
print(list1)

列表推导式

list3 = [i + 1 if i % 2 == 0 else i - 1 for i in list2]
print(list3)
3. 双列表

找出列表中能被3整除的数,组成一个新列表

list1 = []
list2 = [[1, 2, 3], [4, 5, 6], [7, 8]]
for i in list2:
for j in i:
if j % 3 == 0:
list1.append(j)
print(list1)

列表推导式

list2 = [[1, 2, 3], [4, 5, 6], [7, 8]]
list3 = [j for i in list2 for j in i if j % 3 == 0]
print(list3)

找出列表中能被3整除并且大于5的数,组成一个新列表

list2 = [[1, 2, 3], [4, 5, 6], [7, 8]]
list3 = [j for i in list2 for j in i if j % 3 == 0 and j > 5]
print(list3)

找出内层列表长度大于2,在大于2的列表中找能被3整除,组成一个新列表

list1 = []
list2 = [[1, 2, 3], [4, 5, 6], [7, 8]]
for i in list2:
if len(i) > 2:
for j in i:
if j % 3 == 0:
list1.append(j)
print(list1)

列表推导式

list3 = [j for i in list2 if len(i) > 2 for j in i if j % 3 == 0]
print(list3)

​视频链接​


标签:推导,python,list1,list3,list2,print,列表,append
From: https://blog.51cto.com/u_14009243/5975065

相关文章

  • Python爬虫(一)热身
    基础操作一importurllibimportchardet#字符集检测url="http://www.163.com/"html=urllib.urlopen(url)printhtml.headers#头部信息printhtml.getcode()#状态......
  • 当我把用Python做的课堂点名系统献给各科老师后,再也没挂过科
    刚上大学的表弟问我,大学准备好好玩玩,问我有没有什么不挂科的秘诀。哎,这可就问对人了,要想不挂科,先把老师贿赂好,当然,咱们说的贿赂不是送钱啥的,这不是侮辱老师吗?于是我......
  • layui自定义列表文件超链接
    <scripttype="text/html"id="operator_bar_files">{{#layui.each(d.files,function(index,item){}}{{#if(index<=1){}}<ahref="{{window.fil......
  • python中resp.json()与json.loads(str)的区别
    resp=resquests.get(url)print(type(resp))#<class'requests.models.Response'>第一行代码使用requests库发送get请求,得到响应数据resp。第二行代码的输......
  • 读python代码-学到的python
    1.withopen(data_path,'r')asf:withopen()是python用来打开本地文件的,他会在使用完毕后,自动关闭文件,无需手动书写close().三种打开模式:r:只读 用read()w:只写用w......
  • python模块之psutil详解
     一、psutil模块:1.psutil是一个跨平台库(​​http://pythonhosted.org/psutil/​​)能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主......
  • 【python】抽象基类 from abc import ABC, abstractmethod
    abc模块作用Python本身不提供抽象类和接口机制,要想实现抽象类,可以借助abc模块。ABC是Abstract BaseClass的缩写。假设我们定义一些抽象方法,然后子类继承的时候必须要重......
  • 逆向工程 Python 逆向
    逆向工程Python逆向Salarypython逆向https://github.com/SKPrimin/HomeWork/ReverseEngineering/lab1_python(选做)运行Salary.pyc,要求输出flag代表成功。直接运行......
  • python的list的用法
    #ReadMe#本工具是根据用户选择的条目来打印该列表下的内容#例如选择“北京”就会打印北京下面的“海淀”“昌平”“朝阳”,选择“海淀”然后会打印海淀下面的“清华大学”和......
  • Python encode()方法和decode()方法
    Pythonencode()方法encode()方法为字符串类型(str)提供的方法,用于将str类型转换成bytes类型,这个过程也称为“编码”。encode()方法的语法格式如下:str.encode([enco......