我有两个包含列表的列表。我希望missing_cards
中每个列表中的前两项用作master_memory
中的搜索条件。如果它在master_memory
中找到它们,则应打印在master_memory
中找到的列表。如果在master_memory
中找不到它,则会打印“不在主列表中:”,然后在missing_cards
中打印该列表的前2项。
我想要打印:
不可用,位置为:a b已标记
不可用,位置为:a b收藏夹
不在主列表中:c d
不在主列表中:e f
我试过了:
card_name = 0
card_set = 1
card_location = 2
missing_cards=[['a','b','1'],['c','d','1'],['e','f','1']]
master_memory=[['a','b','tagged'],['c','e','slot_1'],['a','b','favorites'],['f','p','slot_2']
for missing_cards_row in missing_cards:
if (missing_cards_row[card_name],missing_cards_row[card_set]) not in master_memory:
print "Not in the Master list:",missing_cards_row[card_name],missing_cards_row[card_set]
else:
for master_memory_row in master_memory:
if missing_cards_row[card_name]==master_memory_row[card_name] and missing_cards_row[card_set]==master_memory_row[card_set]:
print "Not available, location is:",master_memory_row[card_name], master_memory_row[card_set], master_memory_row[card_location]
但这不起作用。它表示missing_cards
中的所有项目都不在master_memory
中,因为它在'master_memory'中找不到该列表,即使我希望它只是查看每个列表中的前两项。想法?
答案 0 :(得分:0)
以下内容如何:
card_name = 0
card_set = 1
card_location = 2
missing_cards=[['a','b','1'],['c','d','1'],['e','f','1']]
master_memory=[['a','b','tagged'],['c','e','slot_1'],['a','b','favorites'],['f','p','slot_2']]
# Assuming missing_cards always has triplets, loop and extract each value
for x,y,z in missing_cards:
# Remember if we had at least one match in master_memory
found = False
# Loop master_memory and check for existance of x y in it
for mm in master_memory:
# Check the first 2 elements
if x in mm and y in mm:
# Print matching location
print "Not available, location is: %s" % ' '.join(mm)
# Flag as found in master_memory
found = True
# Once here, check if that we had at least one match - if not print relevant message
if not found:
print "Not in the Master list: %s %s" % (x, y)
输出:
Not available, location is: a b tagged
Not available, location is: a b favorites
Not in the Master list: c d
Not in the Master list: e f
以上几点假设:
missing_cards
总是三胞胎:
我可以将此更改为for mc in missing_cards
,然后将其用作mc[0]
和mc[1]
进行检查,而不是x
和y
。这样missing_cards
中的项目数可能会有所不同
匹配顺序无关紧要,即(a,b)将匹配(b,a):
如果需要更改,则应使用x in mm
代替x == mm[0] and y == mm[1]
。这样我们还可以确保missing_cards项目在master_memory
答案 1 :(得分:0)
你必须使用嵌套的for循环。
card_name = 0
card_set = 1
card_location = 2
for missing_cards_row in missing_cards:
#This variable will keep track, if the card is found or not
found = false;
for master_memory_row in master_memory:
if(missing_cards_row[card_name]==master_memory_row[card_name] and missing_cards_row[card_set]==master_memory_row[card_set]):
print "Not available, location is:",master_memory_row[card_name], master_memory_row[card_set], master_memory_row[card_location]
found = true
#This flag will inform if the missing card is found in master card or not
if (found==false):
print "Not in the Master list:",missing_cards_row[card_name],missing_cards_row[card_set]