提取列表的内容

时间:2017-09-26 17:42:35

标签: python

我有两个清单和b。我想提取相似和不相似的项目。事情是[i]在b [i]里面,例如[0] == b [0:3]。我在这里尝试的解决方案得到了类似的解决方案(在else语句中)但不是不同的解决方案(if语句)。 if语句创建了多个输入,请指出我所缺少的内容。

a = [[1,2,3], [9,8,3], [1,3,5], [2,3,8], [0,3,5], [5,5,7]]
b = [[1,2,3,4,5,6], [4,5,6,8,6,0], [9,8,3,7,8,9], [5,5,7,0,3,9]]

temp, temp1 = [], []
for i in a:
    for j in b:
        if i != j[0:3]:
            temp.append(j)
        else:
            temp1.append(j)

#print temp should output [[1,3,5], [2,3,8], [0,3,5]] but it gives something different

#print temp1 [[1, 2, 3, 4, 5, 6], [9, 8, 3, 7, 8, 9], [5, 5, 7, 0, 3, 9]] is fine

2 个答案:

答案 0 :(得分:1)

循环的嵌套使得if条件在ai和bj的所有可能组合上执行。而且,根据您在要求中提到的内容,您似乎需要在临时(不是bj)中使用ai的值

您可以使用布尔变量来保存找到/未找到的布尔值,如下所示:

a = [[1,2,3], [9,8,3], [1,3,5], [2,3,8], [0,3,5], [5,5,7]]
b = [[1,2,3,4,5,6], [4,5,6,8,6,0], [9,8,3,7,8,9], [5,5,7,0,3,9]]

temp, temp1 = [], []
for i in a:
    found = False
    for j in b:
        if i != j[0:3]:
            pass
        else:
            found = True
            temp1.append(j)
    if not found :
        temp.append(i)

答案 1 :(得分:0)

a = [[1,2,3], [9,8,3], [1,3,5], [2,3,8], [0,3,5], [5,5,7]]
b = [[1,2,3,4,5,6], [4,5,6,8,6,0], [9,8,3,7,8,9], [5,5,7,0,3,9]]

temp, temp1 = [], []
for i in a:
    for j in b:
        if i != j[0:3]:
            **temp.append(i)
            break**
        else:
            temp1.append(j)