鱼C论坛

 找回密码
 立即注册
查看: 1276|回复: 1

[已解决]python剔除对称重复排列

[复制链接]
发表于 2021-3-29 21:10:59 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
想问各位用Python的itertools模块生成列表排列情况时,必有成对列表满足其中一列表的前半段等于另外一列表的后半段,同时该列表的后半段等于另外这个列表的前半段,如何剔除其中一个?
比方说我用以下代码生成6个元素的全排列列表:
  1. import itertools as it
  2. P = [1,2,3,4,5,6]
  3. list_p = list(it.permutations(P,6))
  4. print(list_p)
复制代码

list_p里面,有[1,2,3,4,5,6]与[4,5,6,1,2,3]这样的“对称对”,请问如何剔除其中一个(比方说剔除[4,5,6,1,2,3],该全排列表的其它排列元组也是类似这样的剔除方式,最后想剔除一半的排列元组生成新的排列列表)?
最佳答案
2021-3-29 23:54:45
本帖最后由 阿奇_o 于 2021-3-30 00:05 编辑

用Python的“魔法命令”: __eq__() , 即可


  1. import itertools as it

  2. P = [1, 2, 3, 4, 5, 6]
  3. list_p = list(it.permutations(P, 6)) # 排列以元组形式,存储在列表中
  4. # print(list_p)
  5. # r_p = tuple(reversed(P)) # 逆序
  6. s_p = tuple(P[3:] + P[:3]) # "对称对"
  7. print(s_p)
  8. # for i in it.permutations(P, 6): # 直接用排列生成器,也可以
  9. new_p = []
  10. for i in list_p:
  11.     if i.__eq__(s_p):
  12.         # print(i)
  13.         continue
  14.     else:
  15.         new_p.append(i)

  16. # print(new_p)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-3-29 23:54:45 | 显示全部楼层    本楼为最佳答案   
本帖最后由 阿奇_o 于 2021-3-30 00:05 编辑

用Python的“魔法命令”: __eq__() , 即可


  1. import itertools as it

  2. P = [1, 2, 3, 4, 5, 6]
  3. list_p = list(it.permutations(P, 6)) # 排列以元组形式,存储在列表中
  4. # print(list_p)
  5. # r_p = tuple(reversed(P)) # 逆序
  6. s_p = tuple(P[3:] + P[:3]) # "对称对"
  7. print(s_p)
  8. # for i in it.permutations(P, 6): # 直接用排列生成器,也可以
  9. new_p = []
  10. for i in list_p:
  11.     if i.__eq__(s_p):
  12.         # print(i)
  13.         continue
  14.     else:
  15.         new_p.append(i)

  16. # print(new_p)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-20 05:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表