2013-06-19 46 views
3

我已經聲明瞭一個我想操作的元組列表。我有一個函數返回用戶的選項。我想看看用戶是否輸入了'A','W','K'中的任何一個鍵。用字典,我會這樣說:while option not in author.items() option = get_option()。我如何用元組列表來完成這個任務?Python - 從元組列表中輸入

authors = [('A', "Aho"), ('W', "Weinberger"), ('K', "Kernighan")] 

回答

2
authors = [('A', "Aho"), ('W', "Weinberger"), ('K', "Kernighan")] 
option = get_option() 
while option not in (x[0] for x in authors): 
    option = get_option() 

這是如何工作:

(x[0] for x in authors)是一個生成器表達式,這由一個從作者名單產生的每個項目之一[0]th元素,然後該元素是對option匹配。一旦發現匹配,它就會短路並退出。

生成器表達式一次產生一個項目,因此內存效率更高。

+0

我剛剛在循環之前初始化了option ='',然後在裏面收到我的選項。這非常有幫助,謝謝! – theGrayFox

+0

+1列表comp。比'zip(* iter)[0]'解決方案好得多。 – HennyH

+0

要獲得與選項相關的名稱,我需要打印作者[選項]? – theGrayFox

1

如何像

option in zip(*authors)[0] 

我們正在使用zip基本上分開的話字母。儘管如此,因爲我們面對的是一個元組的列表,我們必須用*unpack它:

>>> zip(*authors) 
[('A', 'W', 'K'), ('Aho', 'Weinberger', 'Kernighan')] 
>>> zip(*authors)[0] 
('A', 'W', 'K') 

然後我們只需使用option in來測試,如果選項包含在zip(*authors)[0]

+0

我對如何使用這個有點困惑,可以解釋這一點多一點? – theGrayFox

+0

'zip'將返回[元組列表](http://docs.python.org/2/library/functions.html#zip),然後您可以像其他迭代一樣迭代。這確實意味着這裏的語法有點不完整。 – Makoto

+0

@Makoto我不知道我看到了什麼問題。 – arshajii

0

這裏有很好的答案,涵蓋這樣的操作與zip,但你不知道做這樣的 - 你可以使用一個OrderedDict代替。

from collections import OrderedDict 
authors = OrderedDict([('A', "Aho"), ('W', "Weinberger"), ('K', "Kernighan")]) 

因爲它會記住它的輸入順序,你可以遍歷它,不用擔心你的密鑰的奇數或不尋常的排序中。