使用Python中的条件公式迭代列表列表

时间:2014-05-20 04:59:21

标签: python list loops iteration

我有三个输入列表如下:

fill_rgn_pts = [[0,1,2,3,4,5,6,7],[0,1,2,3,4,5],[0,1,2,3],[0,1,2,3]]
fill_rgn = [[region1],[region2],[region3],[region4]]
rooms = [[room1],[room2],[room3],[room4],[room5],[room6]]

我试图根据房间内是否包含所有fill_rgn_pts来配对fill_rgn和房间。这是我到目前为止所尝试的内容:

valid_rooms, valid_fill_rgn, invalid_rooms = [], [], []

for i in rooms:
    for list, region in zip(fill_rgn_pts, fill_rgn):
        if all(i.IsPointInRoom(j) == True for j in list):
            valid_rooms.append(i)
            valid_fill_rgn.append(region)
        else:
            invalid_rooms.append(i)
OUT = valid_fill_rgn, valid_rooms, invalid_rooms

我从这里得到的是三个清单:

valid_fill_rgn = [[region1],[region2],[region3],[region4]]
valid_rooms = [[room1],[room2],[room3],[room4]]
invalid_rooms = [[room1],[room1],[room1],[room2],[room2],[room2],[room3],[room3],[room3],[room4],[room4],[room4],[room4],[room5],[room5],[room5],[room6],[room6],[room6],[room6]]

前两个列表看起来就像我想要的那样,因为他们将我想到的区域和房间配对。然而,第三个列表返回的项目太多。我为每个房间获得了三个额外的值,这让我觉得我正在迭代我不应该做的事情。想法?

2 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,您可以通过将invalid_roomsvalid_rooms更改为 set 来解决此问题,这将不允许重复。

您的循环会为每个点/范围对重复添加,这就是您在valid_roomsinvalid_rooms列表中不断重复的原因。一旦房间被标记为有效或无效,您就不需要再次添加它。

此外,您似乎只有一个项目列表[room1],最好只拥有单独的房间:

rooms = [room1,room2,room3,room4,room5,room6]

答案 1 :(得分:1)

为什么不计算无效房间?

找到有效房间后

fill_rgn_pts = [[0,1,2,3,4,5,6,7],[0,1,2,3,4,5],[0,1,2,3],[0,1,2,3]]
fill_rgn = [[region1],[region2],[region3],[region4]]
rooms = [[room1],[room2],[room3],[room4],[room5],[room6]]

for i in rooms:
    for list, region in zip(fill_rgn_pts, fill_rgn):
        if all(i.IsPointInRoom(j) == True for j in list):
            valid_rooms.append(i)
            valid_fill_rgn.append(region)

invalid_rooms = [room for room in rooms if room not in valid_rooms]
OUT = valid_fill_rgn, valid_rooms, invalid_rooms