【问题标题】:Is there a way to make a function which returns True for certain type elements in a list and False otherwise有没有办法制作一个函数,它为列表中的某些类型元素返回 True,否则返回 False
【发布时间】:2019-04-11 11:40:10
【问题描述】:
我正在尝试定义一个函数,该函数从列表中获取元素,并为首先包含整数的元素返回 True,然后为 '243 abc' 和 '2-4 abc def' 等字符返回 True,对于仅包含 'abc def' 和 @ 等字符的元素返回 False 987654325@
我是编程新手,甚至不知道从哪里开始。因此,经过数小时试图弄清楚一些事情后,我试图在这里提出一个问题。任何帮助,将不胜感激。谢谢。
【问题讨论】:
标签:
python
python-3.x
jupyter-notebook
【解决方案1】:
只需使用isdigit:
>>> my_list = ["abc", "123 abc", "123"]
>>> [s[0].isdigit() for s in my_list]
[False, True, True]
【解决方案2】:
import re
my_list = ["abc", "123 abc", "123"]
new_list = [True if re.match("^[0-9]+.*[A-z]+", x) else False for x in my_list]
查看更多关于正则表达式here 和列表理解here