python 常用代码
时间: 2023-11-17 20:01:42 浏览: 115
Python是一种高级编程语言,具有简单易学、代码简洁、可读性强等特点。以下是Python常用的一些代码:
1. 判断列表中是否有重复元素
```python
def all_unique(lst):
return len(lst) == len(set(lst))
x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6]
y = [1, 2, 3, 4, 5]
all_unique(x) # False
all_unique(y) # True
```
2. 判断两个字符串是否由相同的字符组成
```python
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True
```
3. 获取变量占用的内存大小
```python
import sys
variable = 30
print(sys.getsizeof(variable)) # 24
```
4. 获取字符串占用的字节数
```python
def byte_size(string):
return len(string.encode('utf-8'))
byte_size('') # 4
byte_size('Hello World') # 11
```
5. 打印N次字符串
```python
n = 2
s = "Programming"
print(s * n) # ProgrammingProgramming
```
6. 将字符串的第一个字母大写
```python
s = "programming is awesome"
print(s.title()) # Programming Is Awesome
```
7. 将列表分块
```python
from math import ceil
def chunk(lst, size):
return list(map(lambda x: lst[x * size:x * size + size], list(range(0, ceil(len(lst) / size)))))
chunk([1, 2, 3, 4, 5], 2) # [[1,2],[3,4],5]
```
8. 统计字符串中元音字母的个数
```python
import re
def count_vowels(str):
return len(re.findall(r'[aeiou]', str, re.IGNORECASE))
count_vowels('foobar') # 3
count_vowels('gym') # 0
```
9. 将字符串的第一个字母小写
```python
def decapitalize(string):
return string[:1].lower() + string[1:]
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar') # 'fooBar'
```
10. 展开列表
```python
def flatten(lst):
return [item for sublist in lst for item in sublist]
flatten([[1, 2], [3, 4]]) # [1, 2, 3, 4]
```
阅读全文