Python:在元组中查找字符串

Python:在元组中查找字符串,python,string,variables,Python,String,Variables,我曾试图将我的两个列表(旧代码)更改为一个元组,但我遇到了一些问题(我对不起作用的行进行了评论)。如何使用变量在tupler中查找字符串 def main_tup(): tup = tuple() while True: print "\nMenu for list" print " 1: Insert" print " 2: Lookup" print " 3: Exit program"

我曾试图将我的两个列表(旧代码)更改为一个元组,但我遇到了一些问题(我对不起作用的行进行了评论)。如何使用变量在tupler中查找字符串

def main_tup():
    tup = tuple()

    while True:
        print "\nMenu for list"
        print "  1: Insert"
        print "  2: Lookup"
        print "  3: Exit program"

        choice = raw_input()
        print "Alternative chosen: ", choice

        if choice == "1":
            insert(tup)
        elif choice == "2":
            look(tup)
        elif choice == "3":
            break
        else:
            print "Error: Not a valid choice"

def insert(tup):
    ins = raw_input("Word to insert: ")
    if ins not in tup:                     #doesn't work
        pass
    else:
        print "Error: Word already exist"
        return
    desc = (raw_input("Description of word: "))
    tup = tup + (ins,desc)

def look(tup):
    up = raw_input("Word to lookup: ")
    if up not in tup:                            #doesn't work
        print "Error: Word not found"
        return
    i = 0
    while up != tup[i]:
        i += 2
    if up == tup[i]:
        print "Description of word: ", tup[i+1]

tuple
s是不可变的;当您执行类似于
tup=tup+(ins,desc)
的操作时,它会将本地名称
tup
更改为引用一个全新的
tuple
以及其他内容,但是调用者作为参数传递的
tuple
没有更改(
insert
只是删除了对它的引用)。由于
insert
只更改其
tup
的本地版本而不返回它,因此调用方的(
main\u tup
)tup从不更改;它总是空的
元组(
()


最简单的解决方案是让
insert
return tup
结束,并让调用
insert
更改为
tup=insert(tup)
。您还可以使用
列表
而不是
元组
附加
/
扩展
列表
列表
是可变的,因此如果您没有实际重新分配它们,对
列表
参数的修改也会影响调用方的
列表

如您在下面的代码中所见,
不在
中对元组有效:

>>> t = ('a', 'b', 'c')
>>> 'a' in t
True
>>> 'x' in t
False
>>> 'x' not in t
True
我认为您的问题是另一个:元组是不可变的,因此当在
insert()
方法中操作元组时,
main()
中的
tup
不会更改,并且始终为空

这是元组和列表之间的主要区别之一


要使代码正常工作,您需要将新元组从
insert()
返回到
main()
方法。

谢谢你们提供的有用答案!帮了我大忙