Hướng dẫn python unpack list
Summary: in this tutorial, you’ll learn how to unpack a list in Python to make your code more concise. Show Introduction to the list unpackingThe following example defines a list of strings:
To assign the first, second, and third elements of the list to variables, you may assign individual elements to variables like this:
However, Python provides a better way to do this. It’s called sequence unpacking. Basically, you can assign elements of a list (and also a tuple) to multiple variables. For example:
This statement assigns the first, second, and third elements of the In this example, the number of variables on the left side is the same as the number of elements in the list on the right side. If you use a fewer number of variables on the left side, you’ll get an error. For example:
Error:
In this case, Python could not unpack three elements to two variables. Unpacking and packingIf you want to unpack the first few elements of a list and don’t care about the other elements, you can:
By putting the asterisk (
Output:
This example assigns the first and second elements of the Here’s another example:
Output:
This example assigns the first and second elements to variables. It packs the last two elements in a new list and assigns the new list to the
Summary
Did you find this tutorial helpful ? Unpack trong pythonLink bài viết gốc ở blog của mình: chienkira.github.io/blog/thủ thuật unpack trong python Ký tự Ký hiệu *Unpack chỉ có thể áp dụng lên một object loại iterable, để áp dụng việc cần làm là đặt ký hiệu
Phép unpack với ký hiệu Ví dụ như
Cùng xem qua đoạn code ví dụ sau để hình dung rõ hơn công dụng của unpack.
Unpack đã giúp tách độc lập các phần từ có trong object Đến đây thì nếu liên tưởng chút, ta sẽ thấy cách viết quen thuộc sau hiện lên ở trong đầu.
Vâng chính là nó rồi đó ạ, Nhắc đến ** thôi!Ký hiệu **Unpack khi sử dụng ký hiệu Nó giúp việc truyền một dict vào một method mà chỉ nhận keyword params dễ dàng hơn rất nhiều. Đoạn code demo ví dụ sau sẽ dễ hiểu hơn mọi giải thích dài dòng
Unpack trong các ngôn ngữ khácJavascript ES 6 cũng đã hỗ trợ phép unpack nhưng với tên gọi khác là spread, và sử dụng ký hiệu
Còn trong ruby thì gọi là phép splat, về mặt ký hiệu và cách dùng nó giống như python.
Sử dụng lâu rồi nhưng không hiểu bản chất bên dưới của nhiều đoạn code là phép unpack này, thật là xấu hổ quá. Bài này chủ yếu mang tính sắp xếp lại kiến thức của bản thân. Nếu bạn nào trót vào đọc và thấy chả có khỉ gì thì rất xin lỗi ạ! Link bài viết gốc ở blog của mình: chienkira.github.io/blog/thủ thuật unpack trong python |