首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用其他列表检查列表中数字的顺序?

如何用其他列表检查列表中数字的顺序?
EN

Stack Overflow用户
提问于 2019-06-14 15:36:36
回答 1查看 277关注 0票数 2

我有一个按升序排列的具有以下值的列表。

l1 = 1,3,9

有6个可能的排列,每个置换的长度是l1的长度。

代码语言:javascript
复制
(1, 3, 9)
(1, 9, 3)
(3, 1, 9)
(3, 9, 1)
(9, 1, 3)
(9, 3, 1)

我需要删除所有按照l1命令排列的排列。

1,3,9,3与l1中的顺序匹配。

9,1,3,3与l1中的顺序匹配。

3,9,1,3,9与l1中的顺序匹配。

答案应该是6-3 =3 Mycode:

代码语言:javascript
复制
from itertools import permutations
l = [1,3,9]
perm = permutations(l, len(l))
res = []
for i in list(perm):
    res.append(i)
    for i in res:
    for j in range(0,len(i)):
        if i[j] and i[j+1] in l[j]:
        res.remove(i)
    print(len(res))

我发现输入错误。如何修复这个问题,以及如何修复if语句

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-14 15:46:43

您可以根据原始数据创建相邻元组,并检查您的排列中是否有任何元组位于原始数据的列表中--只有在没有的情况下:添加到结果:

代码语言:javascript
复制
from itertools import permutations
l = [1,3,9]

# create all neighbor-tuples 
tups = set(zip(l,l[1:]))
perm = list(permutations(l, len(l)))
print("perm: ", perm)
res = []
print("tups: ", list(tups))
for i in perm:
    itups = zip(i,i[1:]) # create neighbor tuples from this permutation
    if any( t in tups for t in itups):
        continue
    res.append(i)

print(len(res)) 
print(res)

输出:

代码语言:javascript
复制
perm:  [(1, 3, 9), (1, 9, 3), (3, 1, 9), (3, 9, 1), (9, 1, 3), (9, 3, 1)]
tups:  [(3, 9), (1, 3)]
3
[(1, 9, 3), (3, 1, 9), (9, 3, 1)]

文档:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56601365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档