Python – 交叉连接每个 K 段


在需要交叉聯結每個「K」元素時,可定義使用迭代和擷取索引作為輸出的方法。

範例

以下是它的示範 −

Open Compiler
def merge_pair_elem(my_list_1, my_list_2, K): index_1 = 0 index_2 = 0 while(index_1 < len(my_list_1)): for i in range(K): yield my_list_1[index_1] index_1 += 1 for i in range(K): yield my_list_2[index_2] index_2 += 1 my_list_1 = [24, 13, 82, 22, 65, 74] my_list_2 = [55, 63, 17, 44, 33, 15] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) K = 1 print("The value of K is :") print(K) my_result = [element for element in merge_pair_elem(my_list_1, my_list_2, K)] print("The result is :") print(my_result)

輸出

The first list is :
[24, 13, 82, 22, 65, 74]
The second list is :
[55, 63, 17, 44, 33, 15]
The value of K is :
1
The result is :
[24, 55, 13, 63, 82, 17, 22, 44, 65, 33, 74, 15]

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

說明

  • 定義一個名為「merge_pair_elem」的方法,它將兩個清單和一個「K」值作為參數,並傳回特定的索引作為輸出。

  • 在方法外部,將定義兩個整數清單並顯示在主控台上。

  • 將定義一個「K」值並顯示在主控台上。

  • 清單理解式用於在元素上進行迭代,並且通過傳遞所需參數呼叫該方法。

  • 這會轉換為清單,並指定給變數。

  • 這是在主控台上顯示的輸出。

更新於: 08-Sep-2021

188 次檢視

开启您的职业生涯

完成课程,获得认证

开始
广告