1

下面的代码给出了以特定前缀/后缀开头/结尾的单词:

string_list = [line.strip() for line in open("file.txt", 'r')]
for word in string_list:
    if word[-1] == "a":
        print word

        
string_list = [line.strip() for line in open("file.txt", 'r')]
for word in string_list:
    if word[0] == "fi":
        print word

如何优化它以在大量数据上真正快速?

4

2 回答 2

2

如果word是一个字符串,那么word[0] == "fi"不会做你认为它做的事情。

您可以改为使用startswithandendswith来检查字符后缀和前缀。

string_list = open("file.txt", 'r')

for word in string_list:
    if word.startswith("fi") or word.endswith('a'):
        print word

要将 suffix/ 前缀作为参数传递给脚本,请查看argparse

于 2016-09-19T12:41:40.117 回答
0

如果您需要速度,您可以简单地使用GREP,它是用低级语言编写的,并且肯定比 python 循环快得多。

它也是可移植的,可以在 Linux/Windows/OSX/...

于 2016-09-19T13:09:04.060 回答