python - How to nest 2 for loops into one if statement -
how put 2 loops inside if statement?
ships = [ ["aircraft carrier", 5], ["battleship", 4], ["submarine", 3], ["destroyer", 3], ["patrol boat", 2] ] ships_left = ["a","b","s","d","p"] if [ship ship in ships_left name name in ships if name[0][0] == ship]: print(name[0])
expected output:
aircraft carrier
this because if both iterate once ship should equal "a"
, name should ["aircraft carrier", 5]
, name[0][0]
should "a"
.
how code independently iterate through both lists , branch on given statement associating 2 lists?
calculate ships left first, before using if
test if there any:
left_names = [name name, size in ships if name[0] in ships_left] if left_names: print(left_names[0])
by calculating ships left first, can re-use result both if
test , print()
function; otherwise you'd have make same calculation twice.
you don't need 2 loops; need loop on ships
list , test each name against ships_left
list. i'd make ships_left
set, however, faster membership testing:
ships_left = {"a", "b", "s", "d", "p"}
membership testing in list takes n steps (where n length of list), while in set membership testing takes constant time (o(1)). makes removing ship once it's been sunk (or placed on board) easy , fast too:
ships_left.remove(name[0])
you use next()
function generator expression if need first match; avoids extracting names:
ship_left = next((name name, size in ships if name[0] in ships_left), none) if ship_left: print(ship_left)
demo:
>>> ships = [ ... ["aircraft carrier", 5], ... ["battleship", 4], ... ["submarine", 3], ... ["destroyer", 3], ... ["patrol boat", 2] ... ] >>> ships_left = {"a", "b", "s", "d", "p"} >>> next((name name, size in ships if name[0] in ships_left), none) 'aircraft carrier' >>> ships_left.remove('a') >>> next((name name, size in ships if name[0] in ships_left), none) 'battleship' >>> ships_left.clear() # remove ships >>> next((name name, size in ships if name[0] in ships_left), none) none true
Comments
Post a Comment