Python 程序查找列表中符合给定条件的所有组合

pythonserver side programmingprogramming更新于 2025/10/19 17:16:17

当需要查找列表中符合给定条件的所有组合时,使用简单迭代、append 方法和‘isinstance’方法。

示例

下面是相同的演示 −

my_list = ["python", [15, 12, 33, 14], "is", ["fun", "easy", "better", "cool"]]

print("列表为:")
print(my_list)

K = 4
print("The value of K is :")
print(K)

my_result = []
count = 0
while count <= K - 1:
   temp = []

   for index in my_list:

      if not isinstance(index, list):
         temp.append(index)
      else:
         temp.append(index[count])
   count += 1
   my_result.append(temp)

print("结果为:")
print(my_result)

输出

列表为:
['python', [15, 12, 33, 14], 'is', ['fun', 'easy', 'better', 'cool']]
The value of K is :
4
结果为:
[['python', 15, 'is', 'fun'], ['python', 12, 'is', 'easy'], ['python', 33, 'is', 'better'], ['python', 14, 'is',
'cool']]

解释

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

  • 定义 K 的值并显示在控制台上。

  • 创建一个空列表。

  • 创建一个变量 ‘count’ 并将其赋值为 0。

  • 使用 while 循环遍历列表,并使用 ‘isinstance’ 方法检查元素类型是否与特定类型匹配。

  • 根据此情况,将元素附加到空列表中。

  • 这是显示在控制台上的输出。


相关文章


有用资源