Python列出了相似性

2024-05-15 21:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到两个列表中相似字符的数目。 第一个列表是:

list1=['e', 'n', 'z', 'o', 'a']

第二个列表是用户输入的单词,变成一个列表:

word=input("Enter word")
word=list(word)

我将在下面运行此函数以获取两个列表中的相似数:

def getSimilarItems(word,list1):
       counter = 0
       for i in list2:
           for j in list1:
               if i in j:
                   counter = counter + 1
       return counter

我不知道该怎么做的是如何得到列表中每一项的相似数(这将是0或1,因为单词将被拆分成一个列表,其中一项是字符)

非常感谢您的帮助:)

例如: 如果用户输入的单词是afez: 我想运行函数:

wordcount= getSimilarItems(word,list1)

并将其作为输出:

>>>1 (because a from afez is in list ['e', 'n', 'z', 'o', 'a'])
>>>0 (because f from afez isn't in list ['e', 'n', 'z', 'o', 'a'])
>>>1 (because e from afez is in list ['e', 'n', 'z', 'o', 'a'])
>>>1 (because z from afez is in list ['e', 'n', 'z', 'o', 'a'])

Tags: 函数用户infrom列表iscounter字符
2条回答

听起来你只是想:

def getSimilarItems(word,list1):
    return [int(letter in list1) for letter in word]

What I don't know how to do is how to get the number of similitudes for each item of the list(which is going to be either 0 or 1 as the word is going to be split into a list where an item is a character).

我假设您不计算列表中的项目数,而是希望获得每个元素的单独匹配结果

为此,您可以使用字典或列表,并从函数中返回它们

假设输入与列表长度相同

def getSimilarItems(list1,list2):
     counter = 0
     list = []
     for i in list2:
          for j in list1:
              if i in j:
                  list.append(1)
              else:
                  list.append(0)
     return list

根据你的编辑

def getSimilarItems(list1,list2):
     counter = 0
     for i in list2:
         if i in list1:
             print('1 (because )'+i +' from temp_word is in list'+ str(list1))
         else:
             print("0 (because )"+i +" from temp_word isn't in list" + str(list1))

如果你想要一个更简洁的版本,请看朱利安的答案(我不太擅长列表理解)

相关问题 更多 >