如何在Python中为序列创建子序列,例如[1,2,3],不包括不相邻的子序列(例如[1,3])

发布于 2025-01-04 01:18:37 字数 258 浏览 0 评论 0原文

例如,如果我有序列 [1,2,3],那么生成子序列的算法是什么:

[1]
[2]
[3]
[1,2]
[2,3]
[1,2,3]

但不是

[1,3]

,我也

[3,2]

希望将它们作为字典中的键以及查找的结果插入在数据库中收集这些唯一的子集,形成值。我想知道你能帮忙吗?

非常感谢!

So for example, if I have the sequence [1,2,3], what would be an algorithm to produce the subseqeunces:

[1]
[2]
[3]
[1,2]
[2,3]
[1,2,3]

but not

[1,3]

nor

[3,2]

I'm then hoping to insert these as the keys in a dictionary along with the result from looking up these unique subsets in a database forming the value. I wonder if you could help with that?

Thanks very much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饮惑 2025-01-11 01:18:37
>>> x = [1, 2, 3]
>>> [x[a:b + 1] for a in range(len(x)) for b in range(a, len(x))]
[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]

或者按照您要求的顺序获取它们:

>>> [x[a : a + n] for n in range(1, len(x) + 1)
                  for a in range(0, len(x) - n + 1)]
[[1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]

然后我希望将它们作为键插入字典中

您不能使用列表作为字典中的键,因为字典要求其键是可散列的,而您不能对列表进行散列。

>>> {[1] : 'foo'}
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    {[1] : 'foo'}
TypeError: unhashable type: 'list'

您需要使用元组作为键。

>>> x = [1, 2, 3]
>>> [x[a:b + 1] for a in range(len(x)) for b in range(a, len(x))]
[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]

Or to get them in the order you requested:

>>> [x[a : a + n] for n in range(1, len(x) + 1)
                  for a in range(0, len(x) - n + 1)]
[[1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]

I'm then hoping to insert these as the keys in a dictionary

You can't use lists as keys in a dictionary because a dictionary requires that its keys are hashable and you can't hash lists.

>>> {[1] : 'foo'}
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    {[1] : 'foo'}
TypeError: unhashable type: 'list'

You'll need to use tuples as your keys instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文