繁体   English   中英

Python元组列表(使用键+检查值是否存在)

[英]Python List of Tuples (Find value with key + check if exist)

我有一个元组列表,其中:

TupleList = [("computer", "weird working machine"),("phone","talkerino"),("floor", "walk on")]

而我想做的是,如果我有钥匙,得到打印出来的值

喜欢:

x = raw_input("Word to lookup: ") # I insert "computer"

它应该打印出“奇怪的工作机”

TD LR:通过钥匙获取价值

我需要解决的另一件事是,如果我尝试在元组中附加一个已经存在于元组中的新单词,则应打印“已经存在”,否则应在其后附加新单词。 像这样:

if(word in tuple exist)
    print "Already exist"
else
    TupleOrd.append(((raw_input("\n Word to insert: ").lower()),(raw_input("\n Description of word: ").lower())))

元组不是键值查找的最大数据类型。 考虑改用字典:

>>> TupleList = [("computer", "weird working machine"),("phone","talkerino"),("floor", "walk on")]
>>> d = dict(TupleList)
>>> d["computer"]
'weird working machine'

它还使检查现有单词是否存在变得更加容易:

key = raw_input("Word to insert:").lower()
if key in d:
    print "Sorry, that word is already present"
else:
    d[key] = raw_input("Description of word:").lower()

如果绝对必须使用元组,则可以使用循环搜索键:

for key, value in TupleList:
    if key == "computer":
        print value

并类似地确定哪些键已经存在:

key_exists = False
for key, value in TupleList:
    if key == "computer":
        key_exists = True
if key_exists:
    print "Sorry, that word is already present"
else:
    #todo: add key-value pair to tuple

一种疯狂的方式是:

TupleList = [("computer", "weird working machine"),("phone","talkerino"),("floor", "walk on")]
x = raw_input("Word to lookup: ")
key_exists = next(iter([i[1] for i in TupleList if i[0] == x]), None)) is not None
if key_exists:
    print 'key exists'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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