“cara menyebarkan array dalam python” Kode Jawaban

cara menyebarkan array dalam python

a = [1,2,3]
b = [*a, 4] # [1,2,3,4]
Defiant Dog

Python Array menyebar

As Alexander points out in the comments, list addition is concatenation.

a = [1,2,3,4]
b = [10] + a  # N.B. that this is NOT `10 + a`
# [10, 1, 2, 3, 4]
You can also use list.extend

a = [1,2,3,4]
b = [10]
b.extend(a)
# b is [10, 1, 2, 3, 4]
and newer versions of Python allow you to (ab)use the splat (*) operator.

b = [10, *a]
# [10, 1, 2, 3, 4]
Your choice may reflect a need to mutate (or not mutate) an existing list, though.

a = [1,2,3,4]
b = [10]
DONTCHANGE = b

b = b + a  # (or b += a)
# DONTCHANGE stays [10]
# b is assigned to the new list [10, 1, 2, 3, 4]

b = [*b, *a]
# same as above

b.extend(a)
# DONTCHANGE is now [10, 1, 2, 3, 4]! Uh oh!
# b is too, of course...
Doubtful Dotterel

Jawaban yang mirip dengan “cara menyebarkan array dalam python”

Pertanyaan yang mirip dengan “cara menyebarkan array dalam python”

Lebih banyak jawaban terkait untuk “cara menyebarkan array dalam python” di Python

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya