Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การทำงานของ Repetition Operator บน List ใน Python

ปกติ * แทนคูณ แต่ถ้า operand ซ้ายเป็น list จะกลายเป็น repetition operator ทำหลาย copies ของ list แล้ว join เข้าด้วยกัน สร้าง list ด้วย repetition operator *

ตัวอย่าง

numbers = [0] * 5
print(numbers)

ผลลัพธ์

[0, 0, 0, 0, 0]

[0] list มี 1 element คือ 0 Repetition operator ทำ 5 copies join กัน

ตัวอย่างหลาย elements

numbers = [0, 1, 2] * 3
print(numbers)

ผลลัพธ์

[0, 1, 2, 0, 1, 2, 0, 1, 2]

Python สร้าง shallow copies การเปลี่ยน object ที่หนึ่งจะเปลี่ยนทุกที่ที่ซ้ำ หากไม่ต้องการพฤติกรรมนี้ อย่าใช้ repetition operator สร้าง lists