python各种代码
时间: 2023-11-08 21:01:34 浏览: 80
python 代码
Python是一种高级编程语言,具有简洁、易读、易学的特点。下面是一些常用且实用的Python代码实例:
1. 合并两个字典:
```python
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
# 输出:{'a': 1, 'b': 2, 'c': 3, 'd': 4}
```
2. 计算列表中某个元素的出现次数:
```python
my_list = [1, 2, 3, 2, 4, 2, 5]
count = my_list.count(2)
print(count)
# 输出:3
```
3. 判断一个字符串是否是回文串:
```python
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome('level'))
# 输出:True
```
4. 遍历列表同时获取索引和元素:
```python
my_list = ['a', 'b', 'c', 'd']
for index, value in enumerate(my_list):
print(f'Index: {index}, Value: {value}')
# 输出:
# Index: 0, Value: a
# Index: 1, Value: b
# Index: 2, Value: c
# Index: 3, Value: d
```
5. 反转列表:
```python
my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list)
# 输出:[5, 4, 3, 2, 1]
```
阅读全文