Python 检查它们是否相同

Python 检查它们是否相同,python,string,python-3.x,Python,String,Python 3.x,我想从文本文件中读取并打印首字母相同的前三个单词。我可以得到前3个首字母,但我无法检查它们是否相同 这是我的密码: def main(): f = open("words.txt", "r+") # The loop that prints the initial letters for word in f.read().split(): # the part that takes the 3 initials letters of the word init

我想从文本文件中读取并打印首字母相同的前三个单词。我可以得到前3个首字母,但我无法检查它们是否相同

这是我的密码:

def main():
  f = open("words.txt", "r+")

  # The loop that prints the initial letters
  for word in f.read().split():
     # the part that takes the 3 initials letters of the word
      initials = [j[:3] for j in word.split()]

      print(initials)
words.txt

when, where, loop, stack, wheel, wheeler 

输出

您可以在此处使用字典,前3个字符作为键。范例

when, where, loop, stack, wheel, wheeler 
d={}
f = open("words.txt", "r+")
key_with_three_element=''

for word in f.read().split():
 if word[:3] in d:
    d[word[:3]].append(word)
else:
    d[word[:3]]=[word]
if(len(d[word[:3]])==3):
    key_with_three_element=word[:3]
    break
print(d[key_with_three_element])
输出:

['when', 'where', 'wheel']

您可以使用从前3个字母到单词列表的映射。可以在此处为您节省一些按键操作:

from collections import defaultdict

def get_words():
    d = defaultdict(list)
    with open('words.txt') as f:            
        for line in f:
            for word in line.split(', '):
                prefix = word[:3]
                d[prefix].append(word)
                if len(d[prefix]) == 3:
                    return d[prefix]
    return []

print(get_words())  # ['when', 'where', 'wheel']

此代码段按前3个字母对单词进行分组:

def main():
    # a dict where the first 3 letters are the keys and the
    # values are lists of words
    my_dict = {}

    with open("words.txt", "r") as f:
        for line in f:
            for word in line.strip().split():
                s = word[:3]

                if s not in my_dict:
                    # add 3 letters as the key
                    my_dict[s] = []
                my_dict[s].append(word)

                if len(my_dict[s]) == 3:
                    print(my_dict[s])
                    return

    # this will only print if there are no 3 words with the same start letters
    print(my_dict)

这会停止处理(我使用了一个
return
语句),如果您得到3个具有相同3个字母的单词。

如果文件中没有其他单词共享第一个单词的前三个字母,该怎么办?
def main():
  f = open("words.txt", "r+")

for word in f.read().split():
    record[word[:3]] = record.get(word[:3], [])+[word]
    if len(record[word[:3]]) == 3:
        print (record[word[:3]])
        break