[英]python slice set in list
i would like to slice a set within a list, but every time i do so, i get an empty list in return. 我想在列表中切片集合,但是每次这样做,我都会得到一个空列表。
what i try to accomplish (maybe there is an easier way): 我尝试完成的工作(也许有更简单的方法):
here is my code: 这是我的代码:
result_set = ['1', '2', '3', '4', '5']
result_matrix = []
result_matrix.append(result_set)
slicing the set is no problem: 切片集合没有问题:
print result_set[1:4]
['2', '3', '4']
print result_matrix[:][1:4]
[]
i would expect: 我期望:
[['2', '3', '4']]
>>> result_set = ['1', '2', '3', '4', '5']
>>> print result_set[1:4]
['2', '3', '4']
>>> result_matrix.append(result_set[1:4])
>>> result_matrix
[['2', '3', '4']]
Using result_matrix[:]
returns the whole matrix as it is. 使用result_matrix[:]
返回整个矩阵。 You need to treat the result you want as a part of the array. 您需要将所需结果作为数组的一部分。
>>> result_matrix.append(result_set)
>>> result_matrix[:]
[['1', '2', '3', '4']]
>>> result_matrix[:][0]
['1', '2', '3', '4']
>>> result_matrix[0][1:4]
['2', '3', '4']
Also, as pointed out by falsetru: 另外,如falsetru所指出:
>>> result_matrix.extend(result_set)
>>> result_matrix
['1', '2', '3', '4']
>>> result_matrix[1:4]
['2', '3', '4']
I think this is what you want to do: 我认为这是您想要做的:
>>> target_set = ['2', '3', '4']
>>> any([l for l in result_matrix if target_set == l[1:-1]])
True
>>> target_set = ['1', '2', '3']
>>> any([l for l in result_matrix if target_set == l[1:-1]])
False
Generalising and making that a function: 概括并使其功能:
def is_set_in_matrix(target_set, matrix):
return any(True for l in matrix if list(target_set) == l[1:-1])
>>> result_matrix = [['1', '2', '3', '4', '5']]
>>> is_set_in_matrix(['1', '2', '3'], result_matrix)
False
>>> is_set_in_matrix(['2', '3', '4'], result_matrix)
True
# a quirk - it also works with strings...`
>>> s = '234'
>>> is_set_in_matrix(s, result_matrix)
True
Note that I have used l[1:-1]
to ignore the first and last elements of the "set" in the comparison. 请注意,我已经使用l[1:-1]
来忽略比较中“集合”的第一个和最后一个元素。 This is more flexible should you ever need sets of different lengths. 如果您需要不同长度的组,这将更加灵活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.