2017-09-24 52 views
-1

好,所以問題是我無法弄清楚如何在嘗試添加一個已經存在的單詞時出現「單詞已經存在」。它只是跳過整個事情,只是不斷把現有的單詞放入元組列表中。當一個單詞已經在一個元組中時,Python會打印一條消息

但它應該只是打印「這個詞已經存在」,只是回去而不添加任何新詞。

def instoppning2tup(tuplelista): 
    word = raw_input("Type the word: ") 
    #desc = raw_input("Type the description: ") 
    if word in tuplelista: 
     print "word already exists" 

    else: 
     desc = raw_input("Give descrption to the word: ") 
     tuplelista.append((word,desc)) 

回答

0

你檢查是否wordtuplelista但你添加包含(word, desc)tuplelista一個元組。所以tuplelista樣子:

[(word1, desc1), (word2, desc2), (word3, desc3), ...] 

您應該修改條件:if word in tuplelista:成一個函數調用,這樣的:

if not exists(word, tuplelista)和落實,檢查是否有在tuplelista一個元組具有word作爲一個函數它的第一個元素。

一種方式做到這一點:

def exists(word, tuplelist): 
    return any([x for x in tuplelist if x[0] == word]) 
+0

是的,但「單詞」是代碼的意思,如果它已經在那裏。 –

+1

@johndoe你正在一個包含'tuples'的列表中尋找'string' – alfasin

0

如果您將您的tupelisa到字典中,將有可能:

if word in dict(tupelisa): 
    ... 

它很可能是用字典而不是列表的工作是個好主意的元組,並在最後,如果您需要元組列表,只需將字典轉換爲元組列表

list(yourdic.items()) 
0

你可以使用這樣的事情:

>>> from functools import reduce 
>>> from operator import add 
>>> tuplelista = [('word1', 'description1'), ('word2', 'description2')] 
>>> flat_tuplelista = reduce(add, tuplelista) 
>>> flat_tuplelista 
...['word1', 'description1', 'word2', 'description2'] 

另一種方式

>>> tuplelista = [('word1', 'description1'), ('word2', 'description2')] 
>>> flat_tuplelista = sum(tuplelista,()) 
>>> flat_tuplelista 
...['word1', 'description1', 'word2', 'description2'] 

你可以簡單的檢查:

>>> if word in tuplelista: 
... print "word already exists" 
... else: 
...  desc = raw_input("Give descrption to the word: ") 
...  tuplelista.append((word,desc)) 

順便說一句,在我看來,這將是更好將數據存儲在字典中,其中單詞是關鍵字,描述是一個值。然後,您將可以簡單地檢查該單詞是否在字典中:

>>> words = {'word1': 'desription1', 'word2': 'description2'} 
>>> if word in words: 
... print "word already exists" 
... else: 
...  desc = raw_input("Give descrption to the word: ") 
...  words[word] = desc 
相關問題