简体   繁体   English

在列表中设置的python切片

[英]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): 我尝试完成的工作(也许有更简单的方法):

  • i got a list of sets 我得到了一套清单
  • each set has 5 items 每套有5件
  • i would like to compare a new set against the list (if the set already exists in the list) 我想将新集合与列表进行比较(如果列表中已经存在该集合)
  • the first and the last item in the set is irrelevant for the comparison, so only the positions 2-4 are valid for the search of already existing sets 集合中的第一项和最后一项与比较无关,因此只有位置2-4对于搜索已存在的集合才有效

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM