测试特定元素相对于其他元素的位置 python
test for a specific element placement relative to other elements python
好的,我有一个列表列表,它们是整数。一些子列表只是 [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]
。关于如何实现这一目标的任何想法?
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)
好的,我有一个列表列表,它们是整数。一些子列表只是 [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]
。关于如何实现这一目标的任何想法?
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)