在Python中,单位转换可以通过多种方式实现,具体取决于您想转换的单位类型。以下是一些常见的单位转换示例:
长度单位转换
```python
def length_conversion(value, from_unit, to_unit):
conversion_factors = {
'cm': {'cm': 1, 'dm': 0.1, 'm': 0.01, 'km': 1e-05},
'dm': {'cm': 10, 'dm': 1, 'm': 0.1, 'km': 1e-04},
'm': {'cm': 100, 'dm': 10, 'm': 1, 'km': 0.001},
'km': {'cm': , 'dm': 10000, 'm': 1000, 'km': 1}
}
return value * conversion_factors[from_unit][to_unit]
使用示例
cm_value = 100
converted_value = length_conversion(cm_value, 'cm', 'm')
print(f"{cm_value} cm is equal to {converted_value} m")
数据存储单位转换
```python
class Units(Enum):
B = 1
KB = 1024
KiB = 1024
MB = 1024 * 1024
MiB = 1024 * 1024
GB = 1024 * 1024 * 1024
TB = 1024 * 1024 * 1024 * 1024
def size_b_to_other(size):
units = ['B', 'KB', 'MB', 'GB', 'TB']
for unit in units:
if size < 1024:
break
size //= 1024
return f"{size} {unit}"
def size_other_to_b(size, unit):
units = ['B', 'KB', 'MB', 'GB', 'TB']
index = units.index(unit)
return int(size) * (1024 (len(units) - index - 1))
使用示例
size_in_kb = 5120
size_in_bytes = size_other_to_b(size_in_kb, 'KB')
print(f"{size_in_kb} KB is equal to {size_in_bytes} B")
温度单位转换
```python
def fahrenheit_converter(celsius):
return celsius * 9/5 + 32
使用示例
celsius_value = 30
fahrenheit_value = fahrenheit_converter(celsius_value)
print(f"{celsius_value}°C is equal to {fahrenheit_value}°F")
货币单位转换
```python
def currency_converter(amount, from_currency, to_currency, exchange_rate):
return amount * exchange_rate[from_currency][to_currency]
使用示例
usd_amount = 100
cny_amount = currency_converter(usd_amount, 'USD', 'CNY', {'USD': {'CNY': 6.78}})
print(f"{usd_amount} USD is equal to {cny_amount} CNY")
以上示例展示了如何在Python中进行单位转换。您可以根据需要修改这些示例,以适应不同的单位转换需求。