【问题标题】:test for a specific element placement relative to other elements python测试相对于其他元素python的特定元素放置
【发布时间】:2015-12-12 03:25:28
【问题描述】:

好的,我有一个列表列表,它们是整数。一些子列表只是[0],这是一件好事。我喜欢这些[0],我需要在每个元素!= [0] 之间至少有一个[0]。我一直在努力处理这些for 循环、if 语句和 python 的any() 函数来创建您在下面看到的混乱,虽然它没有给出错误,但它根本不起作用。它没有任何改变。有人对如何解决这个问题有任何建议吗?

for r in range(0,len(combinations)):
        if any( (combinations[r][e] != [0]) and (combinations[r][e-1] != [0]) and (combinations[r][e+1] != [0]) for e in range(1,len(combinations[r])-1)):
            del combination[r]

下面我添加了一个典型combinations 列表的示例。

[([1, 1], [0], [1, 1], [0]),
 ([1, 1], [0], [0], [1, 1]),
 ([1, 1], [1, 1], [0], [0]),
 ([1, 1], [1, 1], [0], [0]),
 ([1, 1], [0], [0], [1, 1]),
 ([1, 1], [0], [1, 1], [0])]

下面是我想要得到的数据类型。

[([1, 1], [0], [1, 1], [0]),
 ([1, 1], [0], [0], [1, 1]),
 ([1, 1], [0], [0], [1, 1]),
 ([1, 1], [0], [1, 1], [0])]

可以看到,父列表中两个相邻的!= [0] 元素列表已经被移除,因为它们之间没有[0]。关于如何做到这一点的任何想法?

【问题讨论】:

    标签: python list if-statement logic element


    【解决方案1】:
    combinations = [([1, 1], [0], [1, 1], [0]),
                ([1, 1], [0], [0], [1, 1]),
                ([1, 1], [1, 1], [0], [0]),
                ([1, 1], [1, 1], [0], [0]),
                ([1, 1], [0], [0], [1, 1]),
                ([1, 1], [0], [1, 1], [0])]
    
    def filterComb(comb):
        result = list()
        for current in comb:
            isok = True
            for i in range(1, len(current)):
                if current[i] != [0] and current[i-1] != [0]:
                    isok = False
                    break
            if isok:
                result.append(current)
        return result
    
    combinations = filterComb(combinations)
    

    【讨论】:

    • 哇!这是令人难以置信! <> 运算符到底是什么?
    • 相当于 !=
    • 我想说总是使用!=。由于<> 不清楚,并且自 Python 3.x 起已被删除。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 2014-12-12
    相关资源
    最近更新 更多