我正在尝试按单词的长度(4 到 8 个字符之间)逐行过滤包含单词的列表。因此,如果输入文件具有:
- 你好
- 沟通
- 是
- 狗
- 测试
输出文件是:
- 你好
- 测试
所以我有这个代码:
dir = "lower.lst"
dict = open(dir, 'r').readlines()
f=open('dictionary','w')
for word in dict:
if len(word)>=4 & len(word)<=8:
f.write(word)
f.close()
print(len(dict))
print(f)
但是输出文件保留了所有单词。 顺便问一下,有没有更有效的方法来做到这一点?
最佳答案
有不止一种选择可以做到这一点。
- 具有filter()内置函数
查看文档 here .
假设您有名为 data
的字符串列表,那么:
data = ['hello', 'communication', 'be', 'dog', 'test']
filtered_list = filter(lambda x: len(x) > 4 and len(x) < 8, data)
print(filtered_list)
将返回:
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
>
['hello']
您可以更改 lambda 函数来过滤不同的条件。过滤器将“捕获”每个返回 True
的元素。
- 具有列表理解
这可能是实现这一目标的最短方法。只需要做:
filtered_list = [x for x in data if len(x) > 4 and len(x) < 8]
关于python - 按单词长度过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53451761/