List and ZIP

list 列印

這裡會包含以下內內容:

  • 基本讀 list 搭配 for
  • *list (快速讀 list 不需要用到 for loop)
  • N 筆後換
  • 轉換 list 到字串(搭配 join)
  • enumerate 方法
  • Method:
    • split
    • slice
    • copy
    • zip
    • 轉換 list 理的 tuple 到 list

常用的方式印 list 內容

list : list = ['A','B','C','D','E','F']

我們可以用以下方法:

- for loop

1
2
3
4
list= [1,2,3]
for i in list:
print(i, end=" ") #
print()

output:

1 2 3

- *list: 不需要 for loop ,可以 unpack list

print(*list) # 新方法

1
2
list= [1,2,3]
print(*list)

output:

1 2 3

- join 和 MAP 方式 轉乘 string

As the join() methods only take in string values, we use the map() methods to convert the integer values into a string before converting the list to a string.

Str 字串 用 join

1
2
flexiple = ["Hire", "the", "top", "python","freelancers"]
print(" ".join(flexiple))

用 map 如果有 str 和 int

1
2
flexiple = ["Hire", "the", "top", 10, "python","freelancers"]
print(" ".join(map(str,flexiple)))

List N 筆後換行\n

如果 N=4 換行:

A B C D
E F

如果 N=2 換行:

A B
C D
E F

- 用 count 方式

1
2
3
4
5
6
7
MY_LIST = [ 'A', 'B', 'C', 'D', 'E', 'F']
cycle = 0
for element in MY_LIST:
cycle += 1
print(element, end=" ")
if cycle % 4 == 0:
print()

- enumerate 方式

Using the enumerate function, we can convert a Python list to a string. Implementing this function, it is possible to iterate over the list and get both the index and value of each element.

1
2
3
4
5
MY_LIST = [ 'A', 'B', 'C', 'D', 'E', 'F']
for cycle, element in enumerate(MY_LIST, start=1):
print(element, end=" ")
if cycle % 4 == 0:
print()

不同 Method

Str to list 把文字轉成 list:

1
2
str = "hello"
list(str)

output:

[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

用 split 把文字轉成 list

1
2
str2="hello world"
str2.split(' ')

output:

[‘hello’, ‘world’]

slicing and copy list

list: name= ["james", "Mary", "john"]

  • slice

    name[:2]

    [‘james’, ‘Mary’]`

x = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > x[-4:-1]

[6, 7, 8]

x[::2]

[0, 2, 4, 6, 8]

  • copy

    newlist = name[:]

    [‘james’, ‘Mary’]

ZIP 方式

Documentation:

where you can iterate serveral iterables (Ex:lists) in parallel.
Return tuple

Example 1: iterate throught list

1
2
listN= [1,2,3]
listStr= ["hello","world","!!!"]
  • using loop to iterate it 2 list out return tuple
1
2
3
#for loop
for item in zip (listN,listStr):
print(item)

output:
(1, ‘hello’)
(2, ‘world’)
(3, ‘!!!’)

  • wrap zip into list return back to orginal list

    list(zip(listN, listStr)) > output:

    [(1, ‘hello’), (2, ‘world’), (3, ‘!!!’)]

  • use * return back to original list, upack the list

    print(list(zip(*zip(listN, listStr)))) > output:

    [(1, 2, 3), (‘hello’, ‘world’, ‘!!!’)]

* unpack everything in the list , it the same as write everything like this:
print(list(zip((1, 'hello'), (2, 'world') ,(3, '!!!'))))

Example2 with different length 長度不同

1
2
3
4
#iterate longest list
import itertools
listA= [1,2,3]
listB= ["hello","w","world","!!!"]

default behavior stop at the end of the shortest list

1
2
for item in itertools.zip_longest(listA, listB):
print(item)

output:

(1, ‘hello’)
(2, ‘w’)
(3, ‘world’)
(None, ‘!!!’)

  • require same length

    Python 3.10 added strict option same length strict=True
    列印會出現錯誤,因為我們的 list 長度不一樣,由於用這個 strict=True就會嚴格判斷

1
2
for item in itertools.zip_longest(listA, listB,strict=True):
print(item)

output:

(1, ‘hello’)
(2, ‘w’)
(3, ‘world’)
Traceback (most recent call last):
File “<stdin>“, line 1, in <module>
ValueError: zip() argument 2 is longer than argument 1

Example 3 iterate list and add in middle

1
2
3
4
5
L1=[4,5,6]
L2=["H","W","!"]
L3=["@","#","%"]
for a, b, c in zip (L1, L2, L3):
print(a, b, c, sep=(" => "))

output:

4 => H => @
5 => W => #
6 => ! => %

Example 4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
prices= [100, 200, 300]
car_size= ["small", "medium", "large"]
colors=["yellow", "green"]

list(zip(prices, car_size, colors))
#[(100, 'small'), (200, 'medium'), (300, 'large')]

#it will use the shortest value
list(zip(prices, car_size, colors)) #convert to list
#[(100, 'small', 'yellow'), (200, 'medium', 'green')]


list(zip(prices))#1 tuple
#[(100,), (200,), (300,)]

list(zip(prices))[0]
#(100,)

Example 5 把 2 個 list 合在一起,寫入檔案

1
2
3
4
5
6
7
a=[0.2342,2.0002,0.1901]
b=[0.4245,0.5123,6.1002]
c = [a, b]
with open("list1.txt", "w") as file:
for x in zip(*c):
print(type(x))
file.write("{0}\t{1}\n".format(*x))

Convert list of tuples into list

如果你有 list 裡面包了 tuple,窯如何把他轉成 list

1
2
3
4
5
6
7
8
9
10
11
12
# [('20221110.112127.316856', '0.000000', '0.000000')]
test= [('20221110.112127.316856', '0.000000', '0.000000')]
print(type(test))
# <class 'list'>
print(test)
#[('20221110.112127.316856', '0.000000', '0.000000')]

# Using itertools
import itertools
out = list(itertools.chain(*test))
print(out)
# ['20221110.112127.316856', '0.000000', '0.000000']

list comprehensions

> square = [x**2 for x in range (1,11)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

pow2 = [2 ** x for x in range(10)] #[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

pow2 = [2 ** x for x in range(10) if x > 5]

[64, 128, 256, 512]

odd = [x for x in range(20) if x % 2 == 1]

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]