주어진 조건으로 리스트에서 모든 조합을 찾아야 할 때 단순 반복, 추가 방법 및 'isinstance' 방법을 사용합니다.
예시
아래는 동일한 데모입니다 -
my_list = ["python", [15, 12, 33, 14], "is", ["fun", "easy", "better", "cool"]]
print("The list is :")
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("The result is :")
print(my_result) 출력
The list is : ['python', [15, 12, 33, 14], 'is', ['fun', 'easy', 'better', 'cool']] The value of K is : 4 The result is : [['python', 15, 'is', 'fun'], ['python', 12, 'is', 'easy'], ['python', 33, 'is', 'better'], ['python', 14, 'is', 'cool']]
설명
-
정수 목록이 정의되고 콘솔에 표시됩니다.
-
K 값이 정의되어 콘솔에 표시됩니다.
-
빈 목록이 생성됩니다.
-
변수 'count'가 생성되고 0에 할당됩니다.
-
while 루프는 목록을 반복하는 데 사용되며 'isinstance' 메서드는 요소 유형이 특정 유형과 일치하는지 확인하는 데 사용됩니다.
-
이에 따라 빈 목록에 요소가 추가됩니다.
-
콘솔에 표시되는 출력입니다.