Skip to main content

数组 List

Declare

import random


food = ["pizza", "carrots", "eggs"]
dinner = random.choice(food)

print(dinner)
dogs = ["Roger", "syd", 1, True]
print("Roger" in dogs) # True
print("Beau" in dogs) # False

dogs[1] # "syd"
dogs[-1] # True
dogs[-2] # 1
dogs[1:2] # "syd"
dogs[:3] # ["Roger", "syd", 1]
dogs[:] # All list

dogs[2] = "Beau"

Methods

Append and remove

dogs.append("Judah")
dogs.extend(["Judah"])
dogs += ["Judah", 5]

dogs.remove("syd")
dogs.pop() # remove last item

Insert

dogs.insert(2, "Test")
dogs[1:1] = ["Test1", "Test2"] # Insert ["Test1", "Test2"] at index 1 position

Sort

items = ["a", "b", "c", "d"]
items.sort()
items.sort(key=str.lower)

items_copy = items[:] # Copy items

print(sorted(items, key=str.lower)) # return a new list, not change original list

找某个 element

index method return position
my_list = ['apple', 'banana', 'cherry']
index = my_list.index('banana') # 返回 1
for loop
my_list = ['apple', 'banana', 'cherry']
for i, item in enumerate(my_list):
if item == 'banana':
print(f"Found 'banana' at index {i}")
my_list = ['apple', 'banana', 'cherry', 'banana']
indexes = [i for i, item in enumerate(my_list) if item == 'banana'] # 返回 [1, 3]