顯示具有 ◇Python 標籤的文章。 顯示所有文章
顯示具有 ◇Python 標籤的文章。 顯示所有文章

2024年11月17日 星期日

[Python] 6/49 Big Lottery 大樂透 程式, 過了今晚!

. [Python] 6/49 大樂透 程式, 過了今晚!.
.
.
import random

lotterys = random.sample(range(1,50), 7)
specialNum = lotterys.pop()

print("大樂透 中獎號碼: ", end="")
for lottery in sorted(lotterys):
    print(lottery, end=" ")
print("\n特別號: ", specialNum)
print("過了今晚!")

執行結果範例:
PS D:\DevTool\ZCode> & C:/Python312/python.exe d:/DevTool/ZCode/_Code/_Python/BigLotterys.py
大樂透 中獎號碼: 13 19 22 34 40 43 
特別號:  32
過了今晚!



2024年10月27日 星期日

[Python] 字典 dict { } 的 key, value 鍵、值 互換

.[Python] 字典 dict { } 的 key, item 鍵、值 互換
 
--- --- --- --- --- --- --- --- ---
(1) 字典鍵值互換, 方法一 for 循環:
mydict = {'a': 1, 'b': 2, 'c': 3}
mydict_new = {}
for key, value in mydict.items():
    mydict_new[value] = key

print(mydict)
print(mydict_new)

---
>>> mydict = {'a': 1, 'b': 2, 'c': 3}
>>> mydict_new = {}
>>> for key, value in mydict.items():
...      mydict_new[value] = key
...
>>> print(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> print(mydict_new)
{1: 'a', 2: 'b', 3: 'c'}
>>>

--- --- --- --- --- --- --- --- ---
(2) 字典鍵值互換, 方法二 列表生成器 generator:
mydict = {'a': 1, 'b': 2, 'c': 3}
mydict_new = dict([value, key] for key, value in mydict.items())
print(mydict)
print(mydict_new)

---
>>> mydict = {'a': 1, 'b': 2, 'c': 3}
>>> mydict_new = dict([value, key] for key, value in mydict.items())
>>> print(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> print(mydict_new)
{1: 'a', 2: 'b', 3: 'c'}

--- --- --- --- --- --- --- --- ---
(3) 字典鍵值互換, 方法三 zip:
mydict = {'a': 1, 'b': 2, 'c': 3}
mydict_new = dict(zip(mydict.values(), mydict.keys()))
print(mydict)
print(mydict_new)

---
>>> mydict = {'a': 1, 'b': 2, 'c': 3}
>>> mydict_new = dict(zip(mydict.values(), mydict.keys()))
>>> print(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> print(mydict_new)
{1: 'a', 2: 'b', 3: 'c'}





[Python] 傳回 ASCII 的 chr() 函數 vs 傳回字元的 Unicode 碼值 ord() 函數

.[Python] 傳回 ASCII 的 chr() 函數 vs 傳回字元的 Unicode 碼值 ord() 函數

(1) 傳回 ASCII 的 chr() 函數:
>>> x1 = 65
>>> x2 = 66
>>> print(chr(x1))  // 或是 print(chr(65))
A
>>> print(chr(x2))  // 或是 print(chr(66))
B
>>>

---
>>> y1 = 97
>>> y2 = 98
>>> print(chr(y1))  // 或是 print(chr(97))
a
>>> print(chr(y2))  // 或是 print(chr(98))
b

.
(2) 傳回字元的 Unicode 碼值 ord() 函數:
>>> ch11 = 'A'
>>> ch12 = 'B'
>>> print(ord(ch11))  // 或是 print(ord( 'A'))
65
>>> print(ord(ch12))  // 或是 print(ord( 'B'))
66
>>>

---
>>> ch21 = 'a'
>>> ch22 = 'b'
>>> print(ord(ch21))  // 或是 print(ord( 'a'))
97
>>> print(ord(ch22))  // 或是 print(ord( 'b'))
98


2024年10月12日 星期六

[Python] name_list.reverse() and name_list[::-1]

(1) 方法1: name_list.reverse()
(2) 方法2: 使用 slice 切片 name_list[::-1]
.
# Example 1:
python3
>>>
>>> cars = ['Honda', 'BMW', 'Toyota', 'Ford']
>>> cars
['Honda', 'BMW', 'Toyota', 'Ford']
>>> cars[::-1]
['BMW', 'Ford', 'Toyota', 'BMW', 'Honda']
>>> cars.reverse()
>>> cars
['Ford', 'Toyota', 'BMW', 'Honda']
.
.
# Example 2:
>>> nums1 = [5, 3, 9, 2]
>>> nums1
[5, 3, 9, 2]
>>> nums2 = nums1[::-1]
>>> nums2
[2, 9, 3, 5]
>>> nums1.reverse()
>>> nums1
[2, 9, 3, 5]
.

2024年3月8日 星期五

[Python] Remove elements from a list

.
[Python] Remove elements from a list
.

(1) Using the del keyword
(2) Using the list.remove(x) method
(3) Using the list.pop([x]) method

... ... ...
(1) Using the del keyword:
# Sample Code 1
list1 = [0, 1, 2, 3, 4, 5, 6]
del list1[0]
print(list1)
# [1, 2, 3, 4, 5, 6]

del list1[-1]
print(list1)
# [1, 2, 3, 4, 5]

del list1[:2]
print(list1)
# [3, 4, 5]


(2) Using the list.remove(x) method:
# Sample Code 2
list1 = [0, 1, 2, 3, 4, 5, 6]
list1.remove(2)
print(list1)
# [0, 1, 3, 4, 5, 6]


(3) Using the list.pop([x]) method:
# Sample Code 3
list1 = [0, 1, 2, 3, 4, 5, 6]
list1.pop()
print(list1)
# [0, 1, 2, 3, 4, 5]
list_removed = list1.pop(4)
print(list1)
# [0, 1, 2, 3, 5]


// End

[Python] Concatenate Lists / Merge Lists in Python

.
[Python] Concatenate Lists / Merge Lists in Python
.

(1) Concatenating Lists with "+" Operator
(2) Utilizing the Extend() Method
(3) Applying the Itertools.chain() Function
(4) Native Method for List Concatenation (list.append())
(5) List Comprehension to concatenate lists

... ... ...

2024年2月23日 星期五

[Python][Regular Expressions][正規表示式] Python’s Regex Symbols

... ... ...
[Regular Expressions][正規表示式] Python’s Regex Symbols
... ... ...


2024年1月1日 星期一

[Python] Python String format 字串格式化 : (1) 舊式字串格式化 %-formatting (2) 新式字串格式化 str.format() (3) 字串插值 f-string (Formatted String Literal) (4) Template Strings

.


Python 在處理字串時, 由於版本的演變, 有太多種方法, 所以很容易搞混. 筆記整理一下.
.


(1) 舊式字串格式化 %-formatting:

string interpolation

初代 format string, 這是類似 C語言 printf 語法, 使用 % 格式, 
例如: %s (字串), %d (十進位整數), %f (浮點數), 將 tuple 中的一組變量依照指定字串格式輸出.

# Example 1.1:
text = 'World'
print('Hello %s' % text)
# Hello world


# Example 1.2:
name = "John"
age = 23
print('%s is %d years old.' % (name, age))
# John is 23 years old.


# Example 1.3:
print('%x' % 11)  # 轉成十六進位
# b

(2) 新式字串格式化 str.format()

Python 2.6 (發布於 2008 年), 開始有新式字串格式化 str.format(), 透過{} 和 format 來代替 % 運算符號.

# Example 2.1:
text = 'World'
print('Hello {0}'.format(text))
# Hello world
print('Hello {}'.format(text))
# Hello world


# Example 2.2:
name = "John"
age = 23
print('{0} is {1} years old.'.format(name, age))
# John is 23 years old.
print('{} is {} years old.'.format(name, age))
# John is 23 years old.


# Example 2.3:
print('{:x}'.format(11))  # 轉成十六進位
# b


# Example 2.4:
print('{:.2f}'.format(3.1416))  # 保留小數點後兩位
# 3.14


# Example 2.5:
print('{:+.2f}'.format(3.1416))  # 帶符號保留小數點後兩位
# +3.14


細節可以參考 Ref3: Python format 格式化函数


(3) 字串插值 f-string (Formatted String Literal)

Python 3.6 (發布於 2016 年) 新增 f-string, 解決變量不易閱讀以及變量超長的問題.

# Example 3.1:
text = 'World'
print(f'Hello {text}')
# Hello world



# Example 3.2:
name = "John"
age = 23
print(f'{name} is {age} years old.')
# John is 23 years old.


# Example 3.3:
print(f'{11:x}')  # 轉成十六進位
# b


# Example 3.4:
print(f'{3.1416:.2f}')  # 保留小數點後兩位
# 3.14
a = 3.1416
print(f'{a:.2f}')  # 保留小數點後兩位
# 3.14


# Example 3.5:
print(f'{3.1416:+.2f}')  # 帶符號保留小數點後兩位
# +3.14


細節可以參考 Ref4: 制霸 Python f-string 各種格式使用方法


(4) Template Strings:

# Example 4.1:
from string import Template
name = 'Bob'
t = Template('Hey, $name!')
t.substitute(name=name)
# 'Hey, Bob!'


--- --- ---

同場加映 : Python String 字串 join() 語法


# Example 5.1:
chars = ['P', 'y', 't', 'h', 'o', 'n']
text = "".join(chars)
print(text)  # 顯示:Python


# Example 5.2:
chars = ['P', 'y', 't', 'h', 'o', 'n']
text = "##".join(chars)
print(text)  # 顯示:P##y##t##h##o##n


# Example 5.3:
words = ["Python", "is", "awesome"]
text = " ".join(words)
print(text)  # 顯示:Python is awesome

Ref2: 如何使用 Python 進行字串格式化

Ref3: Python format 格式化函数

Ref4: 制霸 Python f-string 各種格式使用方法

Ref5: Python String Formatting Best Practices

// End.