gpt4 book ai didi

python 切片在列表中设置

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:43 25 4
gpt4 key购买 nike

我想对列表中的一个集合进行切片,但每次这样做时,我都会得到一个空列表。

我试图完成什么(也许有一个更简单的方法):

  • 我得到了一组列表
  • 每套有 5 件商品
  • 我想将新的集合与列表进行比较(如果该集合已存在于列表中)
  • 集合中的第一项和最后一项与比较无关,因此只有位置 2-4 对于搜索已存在的集合有效

这是我的代码:

result_set = ['1', '2', '3', '4', '5']

result_matrix = []

result_matrix.append(result_set)

切片集合没有问题:

print result_set[1:4]

['2', '3', '4']

print result_matrix[:][1:4]

[]

我期望:

[['2', '3', '4']]

最佳答案

我认为这就是您想要做的:

>>> 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

概括并使其成为一个函数:

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

请注意,我使用了 l[1:-1] 来忽略比较中“集合”的第一个和最后一个元素。如果您需要不同长度的组,这会更加灵活。

关于python 切片在列表中设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25583031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com