如何将列表中的值与嵌套列表的第一个值进行比较并返回嵌套列表结果?

时间:2011-03-31 11:45:01

标签: python compare nested-lists

我有以下两个清单。

清单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"

有关如何做到这一点的任何想法? 感谢

4 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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

答案 2 :(得分: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()

答案 3 :(得分:0)

列表理解中的一个简短的pythonic列表理解:

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