Pin-Jiun / Python

Python Document
0 stars 0 forks source link

2-List and Tuple #2

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago
# 有序可變動列表 List
grades=[12,60,25,70,90]
print(grades)
print(grades[0])
print(grades[3])
print(grades[1:4])
grades=[12,60,25,70,90]
grades[0]=55 # 把 55 放到列表中的第一個位置
print(grades)
grades=[12,60,25,70,90]
grades[1:4]=[] # 連續刪除列表中從編號 1 到編號 4(不包括) 的資料
print(grades)
grades=[12,60,25,70,90]
grades=grades+[12,33]
print(grades)
grades=[12,60,25,70,90] # 取得列表的長度 len(列表資料)
length=len(grades)
print(length)
data=[[3,4,5],[6,7,8]]
print(data[0])
print(data[0][1])
print(data[0][0:2])
print(data)
data[0][0:2]=[5,5,5]
print(data)
# 有序不可變動列表 Tuple
data=(3,4,5)
# data[0]=5 # 錯誤︰Tuple的資料不可以變動
print(data[2])
print(data[0:2])
Pin-Jiun commented 1 year ago

Do not loop over the same list and modify it while iterating!

This is the same code as above except that here we don't loop over a copy. Removing an item will shift all following items one place to the left, thus in the next iteration one item will be skipped. This can lead to incorrect results.

for item in a:
    if even(item):
        a.remove(item)
# --> a = [1, 2, 3] !!!

Also, never modify the index while looping over the list!

This is incorrect because changing i inside the loop will NOT affect the value of i in the next iteration. This example also produces unwanted effects and even lead to IndexErrors like here.

for i in range(len(a)):
    if even(a[i]):
        del a[i]
        i -= 1
# --> IndexError: list index out of range

https://www.python-engineer.com/posts/remove-elements-in-list-while-iterating/

A very common task is to iterate over a list and remove some items based on a condition. This article shows the different ways how to accomplish this, and also shows some common pitfalls to avoid.

Let's say we need to modify the list a and have to remove all items that are not even. We have this little helper function to determine whether a number is even or not.


a = [1, 2, 2, 3, 4]

<p hidden>#more</p>

def even(x):
    return x % 2 == 0

Option 1: Create a new list containing only the elements you don't want to remove

1a) Normal List comprehension

Use list comprehension to create a new list containing only the elements you don't want to remove, and assign it back to a.

a = [x for x in a if not even(x)]
# --> a = [1, 3]

https://www.python-engineer.com/posts/list-comprehension/

1b) List comprehension by assigning to the slice a[:] The above code created a new variable a. We can also mutate the existing list in-place by assigning to the slice a[:]. This approach is more efficient and could be useful if there are other references to a that need to reflect the changes.


a[:] = [x for x in a if not even(x)]
# --> a = [1, 3]

1c) Use itertools.filterfalse()

The itertools module provides various functions for very efficient looping and also offers a method to filter items:

from itertools import filterfalse
a[:] = filterfalse(even, a)
# --> a = [1, 3]

If you really want to keep the for-loop syntax, then you need to iterate over a copy of the list (A copy is simply created by using a[:]). Now you can remove items from the original list if the condition is true.

for item in a[:]:
    if even(item):
        a.remove(item)
# --> a = [1, 3]
Pin-Jiun commented 1 year ago

shallow copy and deep copy


#%% list copy pass by reference
a = [1,2,3]
a_ref = a
a.append(4)
print("a: ", a)
print("a_ref: ", a)

a, a_ref 是完全相同的 a 和 a_ref 的記憶體位置相同, 對 a 做修改,a_ref 也會被改變, 也就是所謂的淺複製

淺複製僅複製容器中元素的地址

b = a #直接賦值是屬於淺複製!!

深複製 deep copy

深複製完全複製了一份副本,容器與容器中的元素地址都不一樣

方法一

b = a[:]

方法二 需要import copy模組,裡面有deepcopy函式可以用

import copy
a = [1, [2,3]]
a_deepcopy = copy.deepcopy(a)
Pin-Jiun commented 8 months ago

How To add Elements to a List in Python append() : append the element to the end of the list. insert() : inserts the element before the given index. extend() : extends the list by appending elements from the iterable. List Concatenation: We can use the + operator to concatenate multiple lists and create a new list.

https://www.digitalocean.com/community/tutorials/python-add-to-list

Pin-Jiun commented 8 months ago

Python List pop()方法 Python 列表 Python 列表

描述 pop() 函數用於移除列表中的一個元素(默認最後一個元素),並且返回該元素的值。

語法 pop()方法語法:

list.pop([index=-1]) 參數 obj -- 可選參數,要移除列表元素的索引值,不能超過列表總長度,默認為 index=-1,刪除最後一個列表值。 返回值 該方法返回從列表中移除的元素對象。

實例 以下實例展示了 pop()函數的使用方法:

實例

!/usr/bin/python3

coding=utf-8

list1 = ['Google', 'Runoob', 'Taobao'] list_pop=list1.pop(1) print "刪除的項為 :", list_pop print "列表現在為 : ", list1 以上實例輸出結果如下:

刪除的項為 : Runoob 列表現在為 : ['Google', 'Taobao']