3

私は次の2つのリストを持っています。

リスト1

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

リスト2

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

4 に答える 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]
于 2011-03-31T11:48:46.770 に答える
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
于 2011-03-31T11:56:44.500 に答える
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()
于 2011-03-31T13:18:23.250 に答える
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))
于 2011-04-01T05:26:36.490 に答える