以上10個要點,請各給一個python程式範例
时间: 2023-08-31 16:28:53 浏览: 58
### 回答1:
1. 計算機器學習的精確度
```python
from sklearn.metrics import accuracy_score
y_true = [0, 1, 1, 0]
y_pred = [0, 1, 0, 1]
accuracy = accuracy_score(y_true, y_pred)
print("Accuracy: ", accuracy)
```
2. 將一個字串反轉
```python
s = "hello world"
s_reversed = s[::-1]
print(s_reversed)
```
3. 計算一個列表中所有元素的總和
```python
nums = [1, 2, 3, 4, 5]
sum_nums = sum(nums)
print(sum_nums)
```
4. 計算一個列表中所有元素的平均值
```python
nums = [1, 2, 3, 4, 5]
avg_nums = sum(nums) / len(nums)
print(avg_nums)
```
5. 將一個列表中的元素進行去重
```python
nums = [1, 2, 3, 2, 4, 3, 5]
unique_nums = list(set(nums))
print(unique_nums)
```
6. 判斷一個數字是否為質數
```python
num = 7
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
```
7. 將一個列表中的元素按照字母順序排序
```python
fruits = ["apple", "orange", "banana", "kiwi"]
sorted_fruits = sorted(fruits)
print(sorted_fruits)
```
8. 將一個字典中的鍵和值對調
```python
d = {"a": 1, "b": 2, "c": 3}
flipped_d = {v: k for k, v in d.items()}
print(flipped_d)
```
9. 將一個列表中的元素都轉化為字串類型
```python
nums = [1, 2, 3, 4, 5]
str_nums = list(map(str, nums))
print(str_nums)
```
10. 將一個字典中所有值都進行平方
```python
d = {"a": 1, "b": 2, "c": 3}
squared_d = {k: v**2 for k, v in d.items()}
print(squared_d)
```
### 回答2:
1. 輸入與輸出
print("Hello, World!")
2. 變數與資料型別
name = "John"
age = 25
print(name + " is " + str(age) + " years old.")
3. 條件判斷
x = 10
if x > 5:
print("x is greater than 5.")
else:
print("x is less than or equal to 5.")
4. 迴圈
for i in range(5):
print(i)
5. 函式
def add(a, b):
return a + b
result = add(3, 5)
print(result)
6. 字串處理
str = "Hello, World!"
print(str.upper())
7. 列表與元組
list = [1, 2, 3, 4, 5]
print(list[2])
tuple = (1, "two", 3.0)
print(tuple[1])
8. 字典
dict = {"name": "John", "age": 25, "city": "New York"}
print(dict["name"])
9. 集合
set = {1, 2, 3, 4, 5}
print(set)
10. 錯誤處理
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
阅读全文