要在Python中合并数组,可以使用以下几种方法:
- 使用"+"操作符合并两个数组:
arr1 = [1, 2, 3] arr2 = [4, 5, 6] combined_arr = arr1 + arr2 print(combined_arr) # 输出:[1, 2, 3, 4, 5, 6]
- 使用extend()方法合并两个数组:
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr1.extend(arr2) print(arr1) # 输出:[1, 2, 3, 4, 5, 6]
- 使用extend()方法合并多个数组:
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr1.extend(arr2 + arr3) print(arr1) # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
- 使用列表解析合并多个数组:
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] combined_arr = [x for arr in [arr1, arr2, arr3] for x in arr] print(combined_arr) # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]