You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python itertools:如何将排列结果打印为垂直列表及Iterable参数疑问

解决方案

直接给你修正后的代码,两种方式任选,都能实现垂直输出所有排列:

方式一:带排列编号和分隔线(更易读)

import itertools

# 先把步骤存成列表,方便后续调用
steps = [
    '1 Download the App and create an app account',
    '2 Choose the station on the map or by searching on the station name in the search field',
    '3 choose connector',
    '4 Choose payment method, and process the payment of the pre-authorization fee',
    '5 Connect the cable to vehicle to start charging',
    '6 Review the price tariff and click on Start Charging'
]

# 获取所有6个步骤的全排列,结果是迭代器,每个元素是一个排列元组
all_permutations = itertools.permutations(steps, 6)

# 逐个输出每个排列,加编号和分隔线
for idx, perm in enumerate(all_permutations, 1):
    print(f"排列 {idx}:")
    print(*perm, sep='\n')
    print('-' * 50)

方式二:极简版(直接输出所有排列)

import itertools

steps = [
    '1 Download the App and create an app account',
    '2 Choose the station on the map or by searching on the station name in the search field',
    '3 choose connector',
    '4 Choose payment method, and process the payment of the pre-authorization fee',
    '5 Connect the cable to vehicle to start charging',
    '6 Review the price tariff and click on Start Charging'
]

# 生成全排列后直接拆分输出,用空行分隔每个排列
all_permutations = itertools.permutations(steps, 6)
print(*all_permutations, sep='\n\n')

关键说明

  • itertools.permutations(steps, 6)会生成所有可能的排列组合,每个组合是一个装着6条步骤的元组,返回的是迭代器类型。
  • 你之前代码里的iterable是未定义的变量,直接替换成这个排列迭代器(或者转成列表list(all_permutations))就行。
  • print(*iterable, sep='\n')里的*是把迭代器里的每个排列拆成单独的打印参数,sep参数用来控制每个排列之间的分隔符,用\n就是换行,用\n\n会加空行,看着更清爽。

内容的提问来源于stack exchange,提问作者maskedraccoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:36:24