python

怎么在Python中合并数组

小亿
255
2024-05-06 13:31:57
栏目: 编程语言

要在Python中合并数组,可以使用以下几种方法:

  1. 使用"+"操作符合并两个数组:
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
combined_arr = arr1 + arr2
print(combined_arr)
# 输出:[1, 2, 3, 4, 5, 6]
  1. 使用extend()方法合并两个数组:
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr1.extend(arr2)
print(arr1)
# 输出:[1, 2, 3, 4, 5, 6]
  1. 使用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]
  1. 使用列表解析合并多个数组:
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]

0
看了该问题的人还看了