从列表获取所有成对组合的 Python 程序


当需要从列表中获取所有成对组合时,会使用与“追加”方法一起进行的迭代。

示例

以下是对此进行演示的情况

Open Compiler
my_list = [15,"John", 2, "Will", 53, 'Rob'] print("The list is :") print(my_list) my_result = [] for i in range(0,len(my_list)): for j in range(0,len(my_list)): if (i!=j): my_result.append((my_list[i],my_list[j])) print("The result is :") print(my_result)

输出

The list is :
[15, 'John', 2, 'Will', 53, 'Rob']
The result is :
[(15, 'John'), (15, 2), (15, 'Will'), (15, 53), (15, 'Rob'), ('John', 15), ('John', 2), ('John', 'Will'), ('John', 53), ('John', 'Rob'), (2, 15), (2, 'John'), (2, 'Will'), (2, 53), (2, 'Rob'), ('Will', 15), ('Will', 'John'), ('Will', 2), ('Will', 53), ('Will', 'Rob'), (53, 15), (53, 'John'), (53, 2), (53, 'Will'), (53, 'Rob'), ('Rob', 15), ('Rob', 'John'), ('Rob', 2), ('Rob', 'Will'), ('Rob', 53)]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义一个列表并将其显示在控制台上。

  • 定义一个空列表。

  • 对原始列表进行迭代,并再次使用双层迭代进行迭代。

  • 当两个索引不相等时,列表的相应元素将追加到空列表中。

  • 这是显示为控制台输出的结果。

更新于:2021 年 9 月 15 日

506 次浏览

启动您的职业

完成课程即可获得认证

开始
广告