出一道与下面代码类似的题Write a function named frequency_of_elements that takes a list and returns the frequency of elements of this list in a dictionary, where the keys are elements, and values are the frequencies of corresponding elements. For example, if the input is ['a',2,'a','b',2], the function should return {'a': 2, 2: 2, 'b': 1}. The order of the keys should be the same as the order of when the elements first appear in the list.
时间: 2024-01-10 16:03:07 浏览: 64
Sure, here's an example code for the `frequency_of_elements` function in Python:
```python
def frequency_of_elements(lst):
frequency_dict = {}
for item in lst:
if item in frequency_dict:
frequency_dict[item] += 1
else:
frequency_dict[item] = 1
return frequency_dict
```
You can call this function by passing a list as an argument, like this:
```python
my_list = ['a', 2, 'a', 'b', 2]
result_dict = frequency_of_elements(my_list)
print(result_dict) # Output: {'a': 2, 2: 2, 'b': 1}
```
This will calculate the frequency of elements in the given list and return a dictionary with the keys as elements and values as their corresponding frequencies. The order of the keys in the output dictionary will be the same as the order of when the elements first appear in the list.
阅读全文