.查找列表和元组中以a或A开头 并且以c结尾的所有元素。 li =["alec", " Aric", "Alex", "Tony", "rain"] tu =("alec", " Aric", "Al
时间: 2024-04-14 07:23:41 浏览: 41
要查找列表和元组中以a或A开头,并且以c结尾的所有元素,可以使用列表推导式或循环遍历的方式进行筛选。以下是两种方法的示例代码:
方法一:使用列表推导式
```python
li = ["alec", "Aric", "Alex", "Tony", "rain"]
tu = ("alec", "Aric", "Alex", "Tony", "rain")
result_li = [item for item in li if (item.startswith("a") or item.startswith("A")) and item.endswith("c")]
result_tu = [item for item in tu if (item.startswith("a") or item.startswith("A")) and item.endswith("c")]
print(result_li) # 输出:['alec', 'Aric']
print(result_tu) # 输出:('alec', 'Aric')
```
方法二:使用循环遍历
```python
li = ["alec", "Aric", "Alex", "Tony", "rain"]
tu = ("alec", "Aric", "Alex", "Tony", "rain")
result_li = []
for item in li:
if (item.startswith("a") or item.startswith("A")) and item.endswith("c"):
result_li.append(item)
result_tu = []
for item in tu:
if (item.startswith("a") or item.startswith("A")) and item.endswith("c"):
result_tu.append(item)
print(result_li) # 输出:['alec', 'Aric']
print(result_tu) # 输出:('alec', 'Aric')
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)