2011-03-31 35 views
3

我有以下兩個列表。如何將列表中的值與嵌套列表的第一個值進行比較並返回嵌套列表結果?

列表1

(a,b,h,g,e,t,w,x) 

列出兩種

((a,yellow),(h,green),(t,red),(w,teal)) 

我想回到上如何做到這一點下面

((a,yellow),(b,null),(h,green),(e,null),(t,red),(w,teal),(x,null)) 

for x in List_1: 
    for y in list_2: 
      if x == y 
      print y 
      else print x, "null" 

任何想法? 感謝

+0

'(a,b,h,g,e,t,w,x)'是一個元組['a,b,h,g,e,t,w,x]'是列表 – 2011-03-31 12:48:02

+0

在你的例子中發生了什麼? – freegnu 2011-04-01 23:11:27

回答

7

給這個一展身手:

a = ('a', 'b', 'h', 'g', 'e', 't', 'w', 'x') 
b = (('a', 'yellow'), ('h', 'green'), ('t', 'red'), ('w', 'teal')) 
B = dict(b) 
print [(x, B.get(x, 'null')) for x in a] 
+0

該死的,打我吧。 – wheaties 2011-03-31 11:50:03

+0

只要你不介意爲字典花費額外的內存,一個很好的解決方案。當需要與列表「b」進行幾次比較時有意義。 – 9000 2011-03-31 11:50:38

0

你的邏輯是正確的。你唯一需要的是形成一個列表,而不是直接打印結果。

如果你堅持嵌套循環(?這是一門功課,右),你需要的東西是這樣的:

list1 = ["a", "b", "h", "g", "e", "t", "w", "x"] 
list2 = [("a", "yellow"), ("h", "green"), ("t", "red"), ("w", "teal")] 

result = [] # an empty list 
for letter1 in list1: 
    found_letter = False # not yet found 
    for (letter2, color) in list2: 
    if letter1 == letter2: 
     result.append((letter2, color)) 
     found_letter = True # mark the fact that we found the letter with a color 
    if not found_letter: 
     result.append((letter1, 'null')) 

print result 
+0

list2的字典轉換可以幫助您避免所有特殊情況代碼以及內部循環和狀態跟蹤。 – freegnu 2011-04-01 23:39:58

+0

這是一個典型的RAM與CPU的權衡(字典轉換是有效的,但仍然花費一點CPU)。 – 9000 2011-04-01 23:42:07

0

另一種方法中做這些

list1 = ["a", "b", "h", "g", "e", "t", "w", "x"] 
list2 = [("a", "yellow"), ("h", "green"), ("t", "red"), ("w", "teal")] 
print dict(((x, "null") for x in list1), **dict(list2)).items() 
0

一個簡短的Python的列表理解列表理解:

[(i, ([j[1] for j in list2 if j[0] == i] or ['null'])[0]) for i in list1] 

更長的版本:

def get_nested(list1, list2): 
    d = dict(list2) 
    for i in list1: 
     yield (i, i in d and d[i] or 'null') 
print tuple(get_nested(list1, list2))