zl程序教程

您现在的位置是:首页 >  Python

当前栏目

Python列表推导式(2)_Python自学第二十四节

2023-02-18 16:43:01 时间

把列表中的所有数据拼接成一个字符串(有不同数据类型),' '.join()方法只可对文本型元素进行拼接,若有数值型则无法进行拼接。以下两种方法可以针对不同类型元素进行拼接:

使用 map()函数

>>> a = [0, 1, 2, 3, 4, 'a', 'b', 'c']
>>> ''.join(map(str,a))
'01234abc'

使用列表推导式

>>> ''.join([str(i) for i in a  ])
'01234abc'

if 进行过滤内容

如下在一堆数值中找出大于0的数值:

>>> a = [1.2,1.3,2,-1,-2,6,9]
>>> [i for i in a if i > 0]   #加上if过滤,输入大于0的元素
[1.2, 1.3, 2, 6, 9]

从列表中找出.py和.sh为后缀的元素:

>>> a = ['test1.py','test2.sh','test3.py','test4.txt']
>>> [i for i in a if i.endswith('.py')]
['test1.py', 'test3.py']

从列表中找出.py和.sh为后缀的元素:把要需要找出的元素定义为一个元组()

>>> [i for i in a if i.endswith(('.py','.sh'))]   #如把.py和.sh放在一个元组
['test1.py', 'test2.sh', 'test3.py']

练习:

编写一个脚本,验证用户输入的IP地址是否合法。 应考虑用户输入的IP地址中可能会有空格。 IP地址应采用点分十进制的形式。 IP地址的每一组数应在0到255之间。

#!/usr/bin/python3
ip = input().strip().split('.')   #strip作用是去除误输入的空格,split作用是以.作为分割符进行分割
key = [i for i in ip if 0<=int(i)<=255]   #作用是限制每个IP元素的范围在0~255,if判断i的值是不是在0~255之间,int把转换为数值型
if len(key) == 4:   #如果key元素的长度为4
  print('yes')   #则输出yes
else:   #其他
  print('no')   #则输出no
---优化后的代码
#!/usr/bin/python3
ip = input().strip().split('.')   
key = [i for i in ip if 0<=int(i)<=255]
print('yes') if len(key) == 4 else print('no')   #用三元表达精简代码