python列表编程题
时间: 2023-06-17 21:02:29 浏览: 41
好的,下面是一些 Python 列表编程题,希望能够帮到你:
1. 给定一个列表,找到列表中的最大值和最小值。
```python
def find_max_min(lst):
max_val = max(lst)
min_val = min(lst)
return max_val, min_val
# 测试
lst = [1, 2, 3, 4, 5]
print(find_max_min(lst)) # (5, 1)
```
2. 给定一个列表,将其中的偶数移动到列表的前面,奇数移动到列表的后面。
```python
def move_even_to_front(lst):
i = 0
j = len(lst) - 1
while i < j:
if lst[i] % 2 == 0:
i += 1
else:
lst[i], lst[j] = lst[j], lst[i]
j -= 1
return lst
# 测试
lst = [1, 2, 3, 4, 5, 6]
print(move_even_to_front(lst)) # [6, 2, 4, 3, 5, 1]
```
3. 给定一个列表,找到列表中的重复元素。
```python
def find_duplicates(lst):
res = []
for i in range(len(lst)):
if lst[i] in lst[i+1:] and lst[i] not in res:
res.append(lst[i])
return res
# 测试
lst = [1, 2, 3, 4, 4, 5, 6, 6]
print(find_duplicates(lst)) # [4, 6]
```
4. 给定两个列表,找到两个列表中的共同元素。
```python
def find_common_elements(lst1, lst2):
res = []
for i in lst1:
if i in lst2 and i not in res:
res.append(i)
return res
# 测试
lst1 = [1, 2, 3, 4, 5]
lst2 = [3, 4, 5, 6, 7]
print(find_common_elements(lst1, lst2)) # [3, 4, 5]
```
5. 给定一个列表,将其中的元素去重。
```python
def remove_duplicates(lst):
res = []
for i in lst:
if i not in res:
res.append(i)
return res
# 测试
lst = [1, 2, 3, 4, 4, 5, 6, 6]
print(remove_duplicates(lst)) # [1, 2, 3, 4, 5, 6]
```