浅谈python输出列表元素的所有排列形式

作者:sayokooo 时间:2023-02-10 11:09:39 

例如:

[‘a', ‘b', ‘c'] 输出 [‘a', ‘b', ‘c'] [‘a', ‘c', ‘b'] [‘b', ‘a', ‘c'] [‘b', ‘c', ‘a'] [‘c', ‘a', ‘b'] [‘c', ‘b', ‘a']

方法一:利用递归的方式实现


def permutation(li):
 len_list = len(li)
 if len_list == 1:
   return li

result = []
 for i in range(len_list):
   res_list = li[:i] + li[i+1:]
   s = li[i]
   per_result = permutation(res_list)
   if len(per_result) == 1:
     result.append(li[i:i + 1] + per_result)
   else:
     result += [[s] + j for j in per_result]
 return result

方法二:利用python自带的模块


import itertools

def permutation(li):
 print(list(itertools.permutations(li)))

补充拓展:python实现四个数字的全排列

首先我们使用常规做法,循环交换完成。


lst = [1, 3, 5, 8]

for i in range(0, len(lst)):
 lst[i], lst[0] = lst[0], lst[i]
 for j in range(1, len(lst)):
   lst[j], lst[1] = lst[1], lst[j]
   for h in range(2, len(lst)):
     print(lst)
   lst[j], lst[1] = lst[1], lst[j]
 lst[i], lst[0] = lst[0], lst[i]

如果列表较长,元素较多,以上常规方法实现起来就比较吃力了,以下我们采用递归方式实现。


def permutations(position):
 if position == len(lst) - 1:
   print(lst)
 else:
   for index in range(position, len(lst)):
     lst[index], lst[position] = lst[position], lst[index]
     permutations(position+1)
     lst[index], lst[position] = lst[position], lst[index]
permutations(0)

来源:https://blog.csdn.net/yezi1993/article/details/84143458

标签:python,输出,列表,排列
0
投稿

猜你喜欢

  • HTML5 声明兼容IE的写法

    2011-06-06 10:34:00
  • TensorFlow 模型载入方法汇总(小结)

    2022-11-09 00:05:42
  • python利用pandas分析学生期末成绩实例代码

    2023-12-13 19:29:08
  • js自定义弹框插件的封装

    2024-05-28 15:38:36
  • 分析Python中解析构建数据知识

    2022-01-12 10:23:48
  • Python将Excel表格按某列拆分为多个sheet实现过程

    2021-06-11 06:59:54
  • WEB前端开发经验总结之实战篇

    2008-06-12 12:49:00
  • pyqt5 从本地选择图片 并显示在label上的实例

    2022-12-12 17:48:04
  • 回顾Javascript React基础

    2023-07-13 00:57:00
  • Python实现base64编码的图片保存到本地功能示例

    2024-01-01 22:58:03
  • 深入解析python中的实例方法、类方法和静态方法

    2022-07-23 09:05:57
  • MySQL中由load data语句引起死锁的解决案例

    2024-01-19 19:37:14
  • SQL进行排序、分组、统计的10个新技巧

    2009-01-23 13:59:00
  • python 实现超级玛丽游戏

    2023-10-10 09:38:38
  • python编程简单几行代码实现视频转换Gif示例

    2021-09-02 03:34:13
  • Python 保存矩阵为Excel的实现方法

    2022-07-23 07:05:00
  • 详解uniapp页面跳转URL传参大坑

    2023-09-15 09:52:43
  • pycharm实现print输出保存到txt文件

    2023-05-09 22:14:20
  • pytorch sampler对数据进行采样的实现

    2023-02-09 20:05:40
  • tensorflow:指定gpu 限制使用量百分比,设置最小使用量的实现

    2021-06-03 17:02:32
  • asp之家 网络编程 m.aspxhome.com