Input list trong Python
Ngày đăng:
03/12/2021
Trả lời:
0
Lượt xem:
265
Show 1- Python List
Trong Python, List là một kiểu dữ liệu linh hoạt nhất. Nó là dẫy (sequence) phần tử (element), nó cho phép loại bỏ, hoặc thêm các phần tử vào danh sách, đồng thời cho phép cắt lát (Slice) các phần tử.
Để viết một danh sách, bạn đặt các phần tử nằm trong cặp ngoặc vuông [ ] và ngăn cách nhau bởi dấu phẩy. Các phần tử trong danh sách được đánh chỉ số (index) từ trái sang phải bắt đầu từ chỉ số 0.
listExample.py
fruitList = ["apple", "apricot", "banana","coconut", "lemen"]
otherList = [100, "one", "two", 3]
print ("Fruit List:")
print (fruitList)
print (" --------------------------- ")
print ("Other List:")
print (otherList)
Output:
Fruit List:
['apple', 'apricot', 'banana', 'coconut', 'lemen']
---------------------------
Other List:
[100, 'one', 'two', 3]
2- Truy cập các phần tử của danh sách
Truy cập các phần tử
Sử dụng vòng lặp for để truy cập vào các phần tử của danh sách:
accessElementExample.py
fruitList = ["apple", "apricot", "banana", "coconut", "lemen", "plum", "pear"]
for fruit in fruitList :
print ("Fruit: ", fruit)
Output:
Fruit: apple
Fruit: apricot
Fruit: banana
Fruit: coconut
Fruit: lemen
Fruit: plum
Fruit: pear
Truy cập thông qua chỉ số (index):
Bạn cũng có thể truy cập vào các phần tử của list thông qua chỉ số. Các phần tử của list được đánh chỉ số từ trái sang phải, bắt đầu từ 0.
indexAccessExample.py
fruitList = ["apple", "apricot", "banana", "coconut", "lemen", "plum", "pear"]
print ( fruitList )
# Số phần tử.
print ("Element count: ", len(fruitList) )
for i in range (0, len(fruitList) ) :
print ("Element at ", i, "= ", fruitList[i] )
# Một danh sách con chứa các phần tử từ index 1 đến 4 (1, 2, 3)
subList = fruitList[1: 4]
# ['apricot', 'banana', 'coconut']
print ("Sub List [1:4] ", subList )
Output:
['apple', 'apricot', 'banana', 'coconut', 'lemen', 'plum', 'pear']
Element count: 7
Element at 0 = apple
Element at 1 = apricot
Element at 2 = banana
Element at 3 = coconut
Element at 4 = lemen
Element at 5 = plum
Element at 6 = pear
Sub List [1:4] ['apricot', 'banana', 'coconut']
Bạn cũng có thể truy cập vào các phần tử của danh sách theo chỉ số âm (Negative index), các phần tử được đánh chỉ số từ phải sang trái với các giá trị -1, -2, ...
indexAccessExample2.py
fruitList = ["apple", "apricot", "banana", "coconut", "lemen", "plum", "pear"]
print ( fruitList )
print ("Element count: ", len(fruitList) )
print ("fruitList[-1]: ", fruitList[-1])
print ("fruitList[-2]: ", fruitList[-2])
subList1 = fruitList[-4: ]
print ("\n")
print ("Sub List fruitList[-4: ] ")
print (subList1)
subList2 = fruitList[-4:-2]
print ("\n")
print ("Sub List fruitList[-4:-2] ")
print (subList2)
Output:
['apple', 'apricot', 'banana', 'coconut', 'lemen', 'plum', 'pear']
Element count: 7
fruitList[-1]: pear
fruitList[-2]: plum
Sub List fruitList[-4: ]
['coconut', 'lemen', 'plum', 'pear']
Sub List fruitList[-4:-2]
['coconut', 'lemen']
3- Cập nhập danh sách
Ví dụ dưới đây là cách cập nhật List theo chỉ số (index):
updateListExample.py
years = [1991,1995, 1992]
print ("Years: ", years)
print ("Set years[1] = 2000")
years[1] = 2000
print ("Years: ", years)
print ( years )
print ("Append element 2015, 2016 to list")
# Nối (append) thêm một phần tử vào cuối danh sách.
years.append( 2015 )
years.append( 2016 )
print ("Years: ", years)
Output:
Years: [1991, 1995, 1992]
Set years[1] = 2000
Years: [1991, 2000, 1992]
[1991, 2000, 1992]
Append element 2015, 2016 to list
Years: [1991, 2000, 1992, 2015, 2016]
Bạn cũng có thể cập nhập giá trị cho một lát (Slice) các phần tử. Đây là cách để bạn cập nhập nhiều phần tử một lúc.
sliceUpdateExample.py
years = [ 1990 , 1991 , 1992 , 1993 , 1994 , 1995 , 1996 ]
print ("Years: ", years)
print ("Update Slice: years[1:5] = [2000, 2001]")
years[1:5] = [ 2000 , 2001 ]
print ("Years: ", years)
Output:
Years: [1990, 1991, 1992, 1993, 1994, 1995, 1996]
Update Slice: years[1:5] = [2000, 2001]
Years: [1990, 2000, 2001, 1995, 1996]
4- Xóa phần tử trong danh sách
Để xóa một hoặc nhiều phần tử trong một danh sách (list) bạn có thể sử dụng lệnh del (del statement), hoặc sử dụng phương thức remove(). Ví dụ dưới đây sử dụng lệnh del để xóa một hoặc nhiều phần tử theo chỉ số.
deleteElementExample.py
years = [ 1990 , 1991 , 1992 , 1993 , 1994 , 1995 , 1996 ]
print ("Years: ", years)
print ("\n del years[6]")
# Xóa phần tử tại vị trí có index = 6.
del years[6]
print ("Years: ", years)
print ("\n del years[1:4]")
# Xóa phần tử tại index = 1,2,3
del years[1:4]
print ("Years: ", years)
Output:
Years: [1990, 1991, 1992, 1993, 1994, 1995, 1996]
del years[6]
Years: [1990, 1991, 1992, 1993, 1994, 1995]
del years[1:4]
Years: [1990, 1994, 1995]
Phương thức remove(value) loại bỏ phần tử đầu tiên trong danh sách có giá trị bằng với giá trị của tham số. Phương thức này có thể ném ra ngoại lệ (throw exception) nếu không tìm thấy phần tử nào để loại bỏ.
removeElementExample.py
years = [ 1990 , 1991 , 1992 , 1993 , 1994 , 1993 , 1993 ]
print ("Years: ", years)
print ("\n years.remove(1993)")
# Loại bỏ phần tử đầu tiên có giá trị 1993 trong danh sách
years.remove(1993)
print ("Years: ", years)
Output:
Years: [1990, 1991, 1992, 1993, 1994, 1993, 1993]
years.remove(1993)
Years: [1990, 1991, 1992, 1994, 1993, 1993]
5- Các toán tử cơ bản cho danh sách
Cũng giống như String, List có 3 toán tử +, * , in.
listOperatorsExample.py
list1 = [1, 2, 3]
list2 = ["One", "Two"]
print ("list1: ", list1)
print ("list2: ", list2)
print ("\n")
list12 = list1 + list2
print ("list1 + list2: ", list12)
list2x3 = list2 * 3
print ("list2 * 3: ", list2x3)
hasThree = "Three" in list2
print ("'Three' in list2? ", hasThree)
Output:
list1: [1, 2, 3]
list2: ['One', 'Two']
list1 + list2: [1, 2, 3, 'One', 'Two']
list2 * 3: ['One', 'Two', 'One', 'Two', 'One', 'Two']
'Three' in list2? False
6- Các hàm liên quan cho List
listsFunctionExample.py
list1 = [1991, 1994, 1992]
list2 = [1991, 1994, 2000, 1992]
print ("list1: ", list1)
print ("list2: ", list2)
# Trả về số lượng phần tử của danh sách.
print ("len(list1): ", len(list1) )
print ("len(list2): ", len(list2) )
# Giá trị lớn nhất trong danh sách (list).
maxValue = max(list1)
print ("Max value of list1: ", maxValue)
# Giá trị nhỏ nhất trong danh sách (list).
minValue = min(list1)
print ("Min value of list1: ", minValue)
# Tuple
tuple3 = (2001, 2005, 2012)
print ("tuple3: ", tuple3)
# Chuyển đổi một Tuple thành List.
list3 = list (tuple3)
print ("list3: ", list3)
Output:
list1: [1991, 1994, 1992]
list2: [1991, 1994, 2000, 1992]
len(list1): 3
len(list2): 4
Max value of list1: 1994
Min value of list1: 1991
tuple3: (2001, 2005, 2012)
list3: [2001, 2005, 2012]
Xem thêm:
7- Các phương thức
Ví dụ:
listMethodsExample.py
years = [ 1990 , 1991 , 1992 , 1993 , 1993 , 1993 , 1994 ]
print ("Years: ", years)
print ("\n - Reverse the list")
# Đảo ngược danh sách.
years.reverse()
print ("Years (After reverse): ", years)
aTuple = (2001, 2002, 2003)
print ("\n - Extend: ", aTuple)
years.extend(aTuple)
print ("Years (After extends): ", years)
print ("\n - Append 3000")
years.append(3000)
print ("Years (After appends): ", years)
print ("\n - Remove 1993")
years.remove(1993)
print ("Years (After remove): ", years)
print ("\n - years.pop()")
# Loại bỏ phần tử cuối cùng của danh sách.
lastElement = years.pop()
print ("last element: ", lastElement)
print ("\n")
# Count
print ("years.count(1993): ",years.count(1993) )
Output:
Years: [1990, 1991, 1992, 1993, 1993, 1993,1994]
- Reverse the list
Years (After reverse): [1994, 1993, 1993, 1993, 1992, 1991, 1990]
- Extend: (2001, 2002, 2003)
Years (After extends): [1994, 1993, 1993, 1993, 1992, 1991, 1990, 2001, 2002, 2003]
- Append 3000
Years (After appends): [1994, 1993, 1993, 1993, 1992, 1991, 1990, 2001, 2002, 2003, 3000]
- Remove 1993
Years (After remove): [1994, 1993, 1993, 1992, 1991, 1990, 2001, 2002, 2003, 3000]
- years.pop(2001)
last element: 3000
years.count(1993): 2
|