Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 遍历列表,忽略重复项_Python_Python 3.x_List_For Loop_Iteration - Fatal编程技术网

Python 遍历列表,忽略重复项

Python 遍历列表,忽略重复项,python,python-3.x,list,for-loop,iteration,Python,Python 3.x,List,For Loop,Iteration,我写了一个程序,试图找到一系列要查找的字母-这些字母代表字母列表中的一个单词,但是它拒绝确认当前3个字母的序列,因为它两次计算第一个列表中的“I”,并将其添加到重复列表中 当前,此代码返回的值不正确,但应返回正确值 letterList= ['F','I', 'I', 'X', 'O', 'R', 'E'] toBeFound = ['F', 'I', 'X'] List = [] for i in toBeFound[:]: for l in letterList[:]:

我写了一个程序,试图找到一系列要查找的字母-这些字母代表字母列表中的一个单词,但是它拒绝确认当前3个字母的序列,因为它两次计算第一个列表中的“I”,并将其添加到重复列表中

当前,此代码返回的值不正确,但应返回正确值

letterList= ['F','I',  'I',  'X',  'O',  'R',  'E']
toBeFound = ['F', 'I', 'X']

List = []
for i in toBeFound[:]:
    for l in letterList[:]:
        if l== i:
            letterList.remove(l)
            List.append(i)
if List == toBeFound:
    print("Correct.")
else:
    print("Incorrect.")

letterList和toBeFound是示例值,其中的字母可以是任何内容。我无法迭代代码并成功确保忽略重复的代码。任何帮助都将不胜感激

一种简单的方法是迭代toBeFound,并查找letterList中的每个元素


基本上,你想看看toBeFound是否是信件列表的一个子集,对吗

这是使用集合的提示:


顺便说一句,[3]和[4]是同一个运算符的不同符号。

我认为这将解决您的问题。请试一试,让我知道

letterList= ['F','I',  'I',  'X',  'O',  'R',  'E']
toBeFound = ['F', 'I', 'X']

found_list = [i for i in toBeFound if i in letterList]

print("Correct" if toBeFound == found_list else "Incorrect")
按要求

letterList= ['F','I',  'I',  'X',  'O',  'R',  'E']
toBeFound = ['F', 'I', 'X']

List = []
for i in toBeFound[:]:
    for l in set(letterList):
        if l== i:
            List.append(i)
if List == toBeFound:
    print("Correct.")
else:
    print("Incorrect.")

这是正确的。我把信单做成了一套!希望有帮助。

您可以将初始列表设置为一组,但是如果您想查找像“hello”这样的单词,它将不起作用,因为您需要两个l

解决这个问题的一个方法是使用字典来检查我们目前的工作情况

letterList = ['H', 'E', 'L', 'X', 'L', 'I', 'O']
toBeFound = ['H', 'E', 'L', 'L', 'O']

# build dictionary to hold our desired letters and their counts
toBeFoundDict = {}
for i in toBeFound:
    if i in toBeFoundDict:
        toBeFoundDict[i] += 1
    else:
        toBeFoundDict[i] = 1

letterListDict = {} # dictionary that holds values from input
output_list = [] # dont use list its a reserved word
for letter in letterList:
    if letter in letterListDict: # already in dictionary

        # if we dont have too many of the letter add it
        if letterListDict[letter] < toBeFoundDict[letter]:
            output_list.append(letter)

        # update the dictionary
        letterListDict[letter] += 1


    else: # not in dictionary so lets add it

        letterListDict[letter] = 1

        if letter in toBeFoundDict:
            output_list.append(letter)



if output_list == toBeFound:
    print('Success')
else:
    print('fail')

这个怎么样:我用python3.6测试过

import collections
letterList= ['F','I',  'I',  'X',  'O',  'R',  'E']
toBeFound = ['F', 'I', 'X']
collections.Counter(letterList)
a=collections.Counter(letterList) # print(a) does not show order
                              # but a.keys() has order preserved
final = [i for i in a.keys() if i in toBeFound]
if final == toBeFound:
    print("Correct")
else:
    print("Incorrect")

如果您希望检查letterList是否按指定顺序包含toBeFound字母,并忽略重复字母,那么这将是旧文件匹配算法的一个简单变体。您可以在如下非破坏性功能中实现它:

def letterMatch(letterList,toBeFound):
    i= 0
    for letter in letterList:
        if letter == toBeFound[i] : i += 1
        elif i > 0 and letter != toBeFound[i-1] : break
        if i == len(toBeFound)    : return True
    return False

letterMatch(['F','I',  'I',  'X',  'O',  'R',  'E'],['F', 'I', 'X'])
# returns True
另一方面,如果您正在寻找的是测试letterList是否具有以任何顺序形成toBeFound所需的所有字母,那么逻辑就简单得多,因为您只需要使用letterList中的字母检查toBeFound的字母:

def lettermatch(letterList,toBeFound):
    missing = toBeFound.copy()
    for letter in letterList:
        if letter in missing : missing.remove(letter)
    return not missing

为什么不将字母列表设置为一组?我猜相对顺序很重要。我建议您将条件从if l==I更改为if l==I,而不是列表中的l:。@bertew您只想删除相邻的重复字母,还是子列表的顺序根本不重要?i、 e.['X',X',F',i']中的['F',i',X']应该是真的吗?这看起来真的是一个问题。你想达到什么目的?如果列表1包含列表2中按该顺序排列的字符。joinlist2 in.joinlist1。如果列表2元素在列表1中?所有[list1中的x代表list2中的x]或其他什么?为什么不只使用列表理解作为发现=[i代表我,如果我在letterList中,则在toBeFound]是的,这是另一种方式。虽然打印不正确或正确需要更多的逻辑。letterList.removel在这里没有区别。是的,你绝对正确。他问我是否可以让他知道我做一盘是什么意思,但他没有看到@保尔特。否则,这将返回他正在寻找的答案。看起来他们在寻找一个子列表,而不是一个子集。例如,如果toBeFound包含类似“hello”的单词,则不能使用子集来查找它。你会被“helo”困住,OP说FIIXORE应该和FIIXORE匹配。这排除了子列表。看,我不认为我同意。在给定的示例中,FIX是所需的单词,输入是FIIXORE。所需单词中没有重复项。我的建议是,如果给你HELLO作为所需的单词,并输入Hemlawll,你可能仍然希望该输入有效,因为它按顺序包含HELLO。根据OP的评论,顺序似乎并不重要。公平地说,我采用的方法实际上并不关心顺序,但是我仍然非常确定它是一个子列表,而不是基于示例的子集
def letterMatch(letterList,toBeFound):
    i= 0
    for letter in letterList:
        if letter == toBeFound[i] : i += 1
        elif i > 0 and letter != toBeFound[i-1] : break
        if i == len(toBeFound)    : return True
    return False

letterMatch(['F','I',  'I',  'X',  'O',  'R',  'E'],['F', 'I', 'X'])
# returns True
def lettermatch(letterList,toBeFound):
    missing = toBeFound.copy()
    for letter in letterList:
        if letter in missing : missing.remove(letter)
    return not missing