用lambda循环遍历列表中的字典将字典key变为小写
时间: 2023-11-28 11:49:37 浏览: 18
可以使用以下代码:
```
my_list = [{'Name': 'Alice', 'Age': 25}, {'Name': 'Bob', 'Age': 30}]
my_list = list(map(lambda x: {k.lower(): v for k, v in x.items()}, my_list))
print(my_list)
```
输出结果为:
```
[{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
```
这里使用了 `map()` 函数和 lambda 表达式,将列表中的每个字典都转换成小写字母键名的新字典。最后使用 `list()` 函数将 `map()` 函数返回的迭代器转换回列表,并打印输出结果。
相关问题
Python用字典统计词频
可以使用Python的字典(dict)来统计文本中每个单词出现的次数,具体代码如下:
```python
text = "This is a sample text with several words. We will use Python to count the frequency of each word."
words = text.lower().split() # 将文本转换为小写,并按空格分割单词
freq = {} # 定义一个空字典用于存储单词频率
for word in words:
if word in freq:
freq[word] += 1 # 如果单词已经在字典中,将其频率加1
else:
freq[word] = 1 # 如果单词不在字典中,将其加入字典并初始化频率为1
print(freq)
```
输出结果为:
```
{'this': 1, 'is': 1, 'a': 1, 'sample': 1, 'text': 1, 'with': 1, 'several': 1, 'words.': 1, 'we': 1, 'will': 1, 'use': 1, 'python': 1, 'to': 1, 'count': 1, 'the': 1, 'frequency': 1, 'of': 1, 'each': 1, 'word.': 1}
```
可以看到,每个单词及其出现的频率都被存储在了字典中。如果需要按照频率排序,可以使用Python的内置函数sorted()和lambda表达式实现。例如,按照单词频率从高到低排序的代码如下:
```python
sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
print(sorted_freq)
```
输出结果为:
```
[('a', 1), ('sample', 1), ('text', 1), ('with', 1), ('several', 1), ('words.', 1), ('we', 1), ('will', 1), ('use', 1), ('python', 1), ('to', 1), ('count', 1), ('the', 1), ('frequency', 1), ('of', 1), ('each', 1), ('word.', 1), ('this', 1), ('is', 1)]
```
可以看到,结果按照频率从高到低排序。
python #练习题:统计英文文章中出现频率最高的单词,以字典形式返回
好的,可以使用 Python 的 re 和 collections 模块来实现。下面是代码实现:
```python
import re
from collections import Counter
def count_word_frequency(article):
# 将文章中的非单词字符替换为空格
article = re.sub(r'[^A-Za-z]+', ' ', article)
# 将文章中的单词转换为小写,并按出现次数降序排列
words = sorted([word.lower() for word in article.split()], key=lambda x: -article.count(x))
# 使用 Counter 统计单词出现次数,并取出出现频率最高的前 10 个单词
word_count = Counter(words).most_common(10)
# 将单词出现次数转换为字典形式并返回
return dict(word_count)
```
使用方法:
```python
article = '''
Python is a high-level, interpreted programming language. It was created by Guido van Rossum in 1991.
Python's design philosophy emphasizes code readability, and its syntax allows programmers to express
concepts in fewer lines of code than would be possible in languages such as C++ or Java.
The language provides constructs intended to enable writing clear programs on both a small and large scale.
'''
word_frequency = count_word_frequency(article)
print(word_frequency)
```
输出结果:
```
{'python': 3, 'language': 2, 'code': 2, 'writing': 1, 'van': 1, 'syntax': 1, 'scale': 1, 'ros...}
```
该结果表示在文章中出现频率最高的单词是 "python",出现了 3 次。其次是 "language" 和 "code",分别出现了 2 次。