使用python语言list1=['1234','abc',' ','*?/'] (1)只保留list1中的数字字符串 (2)只保留非None的值
时间: 2023-06-09 13:04:47 浏览: 52
回答:
对于问题(1),可以使用正则表达式来筛选出数字字符串,代码如下:
```
import re
list1 = ['1234', 'abc', ' ', '*?/']
digit_list = [s for s in list1 if re.match(r'^\d+$', s)]
print(digit_list)
```
输出结果为:
```
['1234']
```
对于问题(2),可以使用列表推导式和 `is not None` 来筛选出非 None 的值,代码如下:
```
list2 = [1, None, 'hello', 3.5, None]
non_none_list = [x for x in list2 if x is not None]
print(non_none_list)
```
输出结果为:
```
[1, 'hello', 3.5]
```
相关问题
python 如何模糊匹配list中的字符串
可以使用正则表达式模块re来实现模糊匹配,具体步骤如下:
1. 导入re模块
```python
import re
```
2. 定义匹配模式
```python
pattern = re.compile("要匹配的模式")
```
其中,"要匹配的模式"可以是一个正则表达式,如"abc.*"表示以"abc"开头,后面跟任意字符的字符串。
3. 对list中的每个字符串进行匹配
```python
result = []
for item in my_list:
if pattern.match(item):
result.append(item)
```
其中,pattern.match(item)表示对item进行匹配,如果匹配成功则返回一个Match对象,否则返回None。
完整代码示例:
```python
import re
my_list = ["abc", "abcdef", "xyz", "123abc", "aabbcc"]
pattern = re.compile("abc.*")
result = []
for item in my_list:
if pattern.match(item):
result.append(item)
print(result) # ['abc', 'abcdef', '123abc']
```
上述代码中,结果为['abc', 'abcdef', '123abc'],即所有以"abc"开头的字符串。
python提取字符串中数字
可以使用正则表达式来提取字符串中的数字,例如:
```python
import re
string = 'abc123def456ghi789'
numbers = re.findall('\d+', string)
print(numbers)
```
输出:
```
['123', '456', '789']
```
其中,`\d` 表示匹配任意数字字符,`+` 表示匹配一个或多个数字字符,`findall` 函数返回所有匹配的结果。如果需要将结果转换为整数类型,可以使用 `map` 函数:
```python
numbers = list(map(int, numbers))
print(numbers)
```
输出:
```
[123, 456, 789]
```