python字典与列表结合编程题
1. 给定一个列表,统计列表中各元素的出现次数,并以字典的形式返回结果。
```python
def count_elements(lst):
count_dict = {}
for element in lst:
if element in count_dict:
count_dict[element] += 1
else:
count_dict[element] = 1
return count_dict
print(count_elements([1, 2, 3, 2, 1, 3, 4, 5, 4, 4])) # 输出: {1: 2, 2: 2, 3: 2, 4: 3, 5: 1}
```
lambda编程2. 给定一个字典,统计字典中各键的值的和,并以字典的形式返回结果。
```python
def sum_values(dictionary):
sum_dict = {}
for key in dictionary:
if isinstance(dictionary[key], int):
sum_dict[key] = dictionary[key]
elif isinstance(dictionary[key], list):
sum_dict[key] = sum(dictionary[key])
return sum_dict
dictionary = {'a': 10, 'b': [1, 2, 3], 'c': 5}
print(sum_values(dictionary)) # 输出: {'a': 10, 'b': 6, 'c': 5}
```
3. 字典列表排序:给定一个字典列表,根据字典中某个键的值进行排序。
```python
def sort_dicts(dicts, key):
return sorted(dicts, key=lambda x: x[key])
dicts = [{'name': 'Tom', 'age': 25}, {'name': 'Jerry', 'age': 30}, {'name': 'Alice', 'age': 20}]
print(sort_dicts(dicts, 'age')) # 输出: [{'name': 'Alice', 'age': 20}, {'name': 'Tom', 'age': 25}, {'name': 'Jerry', 'age': 30}]
```
4. 列表字典去重:给定一个列表字典,去除重复的字典。
```python
def deduplicate_list_of_dicts(lst):
return [dict(t) for t in {tuple(d.items()) for d in lst}]
lst = [{'name': 'Tom', 'age': 25}, {'name': 'Jerry', 'age': 30}, {'name': 'Tom', 'age': 25}]
print(deduplicate_list_of_dicts(lst)) # 输出: [{'name': 'Tom', 'age': 25}, {'name': 'Jerry', 'age': 30}]
```
5. 字典列表按字典中某个键的值进行分组。
```python
def group_dicts(dicts, key):
groups = {}
for d in dicts:
if d[key] not in groups:
groups[d[key]] = [d]
else:
groups[d[key]].append(d)
return groups
dicts = [{'name': 'Tom', 'age': 25}, {'name': 'Jerry', 'age': 30}, {'name': 'Alice', 'age': 25}]
print(group_dicts(dicts, 'age')) # 输出: {25: [{'name': 'Tom', 'age': 25}, {'name': 'Alice', 'age': 25}], 30: [{'name': 'Jerry', 'age': 30}]}
```
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论