如何将2 for for循环到一个if语句中

时间:2016-04-19 09:32:17

标签: python python-3.x if-statement for-loop

如何在if语句中放置2个for循环?

Ships = [
    ["Aircraft Carrier", 5], 
    ["Battleship", 4], 
    ["Submarine", 3],    
    ["Destroyer", 3], 
    ["Patrol Boat", 2]
]
ships_left = ["A","B","S","D","P"]

if [ship for ship in ships_left name for name in Ships if name[0][0] == ship]:
    print(name[0])

预期产出:

Aircraft Carrier

这是因为如果他们都迭代一次,那么发货应该等于"A",名称应该是["Aircraft Carrier", 5],所以name[0][0]应该是"A"

你会如何为它做这个代码来独立地遍历两个列表并在给定的两个列表关联的语句上进行分支?

1 个答案:

答案 0 :(得分:2)

在使用if测试是否存在之前计算首先>的船只

left_names = [name for name, size in Ships if name[0] in ships_left]
if left_names:
    print(left_names[0])

通过计算首先留下的船只,您可以重复使用if测试和print()功能的结果;否则你必须进行两次相同的计算。

你也不需要两个循环;您只需要遍历Ships列表并根据ships_left列表测试每个名称。但是,为了更快的成员资格测试,我需要设置ships_left

ships_left = {"A", "B", "S", "D", "P"}

列表中的成员资格测试最多需要N个步骤(其中N是列表的长度),而在集合中,成员资格测试需要恒定的时间(O(1))。这使得一旦船舶沉没(或放置在船上)后也能轻松快速地移除船舶:

ships_left.remove(name[0])

如果您只需要第一个匹配,则可以将next()函数与生成器表达式一起使用;这可以避免提取所有名称:

ship_left = next((name for name, size in Ships if name[0] in ships_left), None)
if ship_left:
    print(ship_left)

演示:

>>> Ships = [
...     ["Aircraft Carrier", 5],
...     ["Battleship", 4],
...     ["Submarine", 3],
...     ["Destroyer", 3],
...     ["Patrol Boat", 2]
... ]
>>> ships_left = {"A", "B", "S", "D", "P"}
>>> next((name for name, size in Ships if name[0] in ships_left), None)
'Aircraft Carrier'
>>> ships_left.remove('A')
>>> next((name for name, size in Ships if name[0] in ships_left), None)
'Battleship'
>>> ships_left.clear()  # remove all ships
>>> next((name for name, size in Ships if name[0] in ships_left), None) is None
True