当一个单词已经在元组中时,Python会打印一条消息

时间:2017-09-24 19:40:40

标签: 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) )

3 个答案:

答案 0 :(得分:0)

您正在检查word是否在tuplelista中,但是您在(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]) 

答案 1 :(得分:0)

如果您将tupelisa转换为字典,则可以:

if word in dict(tupelisa):
   ...

使用字典而不是元组列表可能是个好主意,最后,如果你需要元组列表,只需将字典转换为元组列表

list(yourdic.items())

答案 2 :(得分: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) )

顺便说一下,在我看来,将数据存储在字典中会更好,其中word是键,而description是一个值。然后,您将能够简单地检查单词是否在字典中:

>>> 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