简体   繁体   中英

Python printing a message when a word is already in a tuple

Ok so the problem is I can't figure out how to get the "word already exists" to appear when trying to add a already existing word. It just skips the whole thing and just keeps putting the already existing word into the tuple list.

But it should just print that "the word already exists" and just go back without adding any new words.

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

You're checking if the word is in tuplelista but you add a tuple that contains (word, desc) into the tuplelista . So tuplelista looks like:

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

You should modify the condition: if word in tuplelista: into a function call, something like:

if not exists(word, tuplelista) and implement a function that checks if there is a tuple in the tuplelista that has word as its first element.

One way to do it:

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

If you convert your tupelisa to dictionary it will be possible:

if word in dict(tupelisa):
   ...

it will be probably a good idea to work with dictionary instead of list of tuples and at the end, if you need list of tuples just convert dictionary to list of tuples

list(yourdic.items())

You can use something like this:

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

Another way

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

And you can simply check:

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

Btw, it seems to me, it will be better to store data in dictionary, where word is a key, and description is a value. And then, you will be able to simply check if the word is in dictionary:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM