小小python代码段(12处有疑问,欢迎大家指教)

  1. 反转字符串(利用切片 slice)
my_string = 'miss you baby, but take your time'
reversed_string = my_string[::-1] # [x: y: z] x为切片起始位置,y为结束位置,z为间隔
print(reversed_string)
  1. 查找字符串的唯一要素(不重复输出元素)
    函数set()
my_string = 'aaabbbcccddd'
elements = set(my_string)
print(elements)
#output {'c', 'd', 'a', 'b'} (任意顺序)
  1. 两个变量值的交换(3种方法)
#way1 引入中间变量
a = 1
b = 2
c = a
a = b
b = c
print('a = ' + str(a))
print('b = ' + str(b))
#way2 加减法
a = 1
b = 2
a = a + b
b = a - b
a = a - b
print('a = ' + str(a))
print('b = ' + str(b))
#way3 python
a, b = 1, 2 #python 特殊的赋值方法
a, b = b, a #python 两个变量的值的交换
print('a = ' + str(a))
print('b = ' + str(b))
  1. 字符串拆分成子字符串列表
    方法 .spilt()
my_string = 'miss you baby, but take your time'
print(my_string.split())
print(my_string.split(','))
#output
['miss', 'you', 'baby,', 'but', 'take', 'your', 'time'] #默认为以" "分隔
['miss you baby', ' but take your time']#设定以","分隔
  1. 将分隔的字符串整合为单个字符串
    方法 .join()
my_string = 'miss you baby, but take your time'
separated_string = my_string.split()
combined_string1 = ' '.join(separated_string)
combined_string2 = ','.join(separated_string)
print(combined_string1) #以" "整合
print(combined_string2) #以","整合
  1. 检查字符串是否回文(Palindrome)
    原字符串是否与反字符串相等
my_string = '上海自来水来自海上'
if my_string == my_string[::-1]:
    print('the string is a palindrome')
else:
    print('the string not a palindrome')
  1. 列表的要素频率
    调用 collections 中的 Counter类
    Counter() 反馈一个字典 键为元素 值为频率
    方法.most_common() 频率最多的元素
from collections import Counter
my_list = ['a', 'b', 'c', 'c', 'd', 'd', 'd']
count = Counter(my_list)
print(count)
print(count['c'])
print(count.most_common(1))
#output
Counter({'d': 3, 'c': 2, 'a': 1, 'b': 1}) #整个字典
2 #指定键的值
[('d', 3)] #从大到小. 如果count.most_common(2) 则,输出从大到小的两个元素
  1. 检查两个字符串是否为anagrams(同字母不同序)
    应用Counter类
from collections import Counter
str_1 = 'abcd'
str_2 = 'cadb'
cnt_1 = Counter(str_1)
cnt_2 = Counter(str_2)
if cnt_1 == cnt_2:
    print('two strings are anagrams')
else:
    print('two strings are not anagrams')
  1. try-except-else-finally块(!!!)
print('to calculate a/b')
a = int(input('a = '))
b = int(input('b = '))
try: 
    c = a/b
except ZeroDivisionError: #如果发生...
    print('please check your divisor!')
else: #除了except的情况外...
    print('a/b = ' + str(c))
finally: #必执行!
    print('the end')

10.利用列举获取索引和值对
函数enumerate()

my_list = ['a', 'b', 'c', 'd', 'e', 'f']
for index, item in enumerate(my_list, 0): #形参0可选,0为默认值,若为1,则从1开始计数
    print(index, item)
#output
0 a
1 b
2 c
3 d
4 e
5 f
  1. 检查对象内存的使用
    模块sys 方法.getsizeof()
import sys
num = 666
print(sys.getsizeof(num)) #output 不同ide占用内存不同
  1. 合并两个字典
    combined_dict = {**dict + **dict}
dict_1 = {'apple': 9,
          'banana': 10}
dict_2 = {'banana': 9,
          'grape': 11}
combined_dict = {**dict_1, **dict_2}

print(combined_dict) #查看列表

for key, value in combined_dict.items(): #遍历列表
    print(key, value)
#output
{'apple': 9, 'banana': 9, 'grape': 11}#有交叉的情况 'banana'的值为第二个(最后)字典值?
apple 9
banana 9
grape 11
  1. 整数转化为数字列表
#way1 函数map()
num = 123456
list_digits1 = list(map(int, str(num)))
print(list_digits1)
#way2 解析列表list comprehension
list_digits2 = [int(x) for x in str(num)]
print(list_digits2)

14.检查元素是否唯一
set()

my_list = ['a', 'b', 'c', 'd']
if len(my_list) == len(set(my_list)):
    print('all elements of list are unique')
else:
    print('list has duplicates')
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页