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

3

I have the following two lists.

List 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"

有没有关于如何做到这一点的想法? 谢谢

(a,b,h,g,e,t,w,x) 是一个元组,[a,b,h,g,e,t,w,x] 是一个列表。 - John La Rooy
你的示例中的 g 发生了什么事? - freegnu
4个回答

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]

只要您不介意为字典花费额外的内存,这是一个很好的解决方案。当您需要对列表b进行多次比较时,这种方法就很有意义了。 - 9000

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的字典转换可以避免所有特殊情况代码、内部循环和状态跟踪。 - freegnu
这是典型的RAM与CPU之间的权衡(字典转换很高效,但仍需要一点CPU成本)。 - 9000

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

列表推导式中的简短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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接