当前位置:   article > 正文

Python代码之合并两个字典、链式比较、重复打印字符串等

Python代码之合并两个字典、链式比较、重复打印字符串等

1、合并两个字典

Python3.5之后,合并字典变得容易起来。我们可以通过**符号解压字典,并将多个字典传入{}中,实现合并。

  1. def Merge(dict1, dict2):
  2. res = {**dict1, **dict2}
  3. return res
  4. # 两个字典
  5. dict1 = {"name": "Joy", "age": 25}
  6. dict2 = {"name": "Joy", "city": "New York"}
  7. dict3 = Merge(dict1, dict2)
  8. print(dict3)

输出:

{'name': 'Joy', 'age': 25, 'city': 'New York'}

2、链式比较

python有链式比较的机制,在一行里支持多种运算符比较。相当于拆分多个逻辑表达式,再进行逻辑与操作。

  1. a = 5
  2. print(2 < a < 8)
  3. print(1 == a < 3)

输出:

  1. True
  2. False

3、重复打印字符串

将一个字符串重复打印多次,一般使用循环实现,但有更简易的方式可以实现。

  1. n = 5
  2. string = "Hello!"
  3. print(string * n)

输出:

Hello!Hello!Hello!Hello!Hello!

4、检查文件是否存在

我们知道Python有专门处理系统交互的模块-os,它可以处理文件的各种增删改查操作。

那如何检查一个文件是否存在呢?os模块可以轻松实现。

  1. from os import path
  2. def check_for_file():
  3. print("Does file exist:", path.exists("data.csv"))
  4. if __name__=="__main__":
  5. check_for_file()

输出:

Does file exist: False

5、检索列表最后一个元素

在使用列表的时候,有时会需要取最后一个元素,有下面几种方式可以实现。

  1. my_list = ['banana', 'apple', 'orange', 'pineapple']
  2. #索引方法
  3. last_element = my_list[-1]
  4. #pop方法
  5. last_element = my_list.pop()

输出:

'pineapple'

6、列表推导式

列表推导式是for循环的简易形式,可以在一行代码里创建一个新列表,同时能通过if语句进行判断筛选

  1. def get_vowels(string):
  2. return [vowel for vowel in string if vowel in 'aeiou']
  3. print("Vowels are:", get_vowels('This is some random string'))

输出:

Vowels are:  ['i', 'i', 'o', 'e', 'a', 'o', 'i']

7、计算代码执行时间

python中time模块提供了时间处理相关的各种函数方法,我们可以使用它来计算代码执行的时间。

  1. import time
  2. start_time = time.time()
  3. total = 0
  4. for i in range(10):
  5. total += i
  6. print("Sum:", total)
  7. end_time = time.time()
  8. time_taken = end_time - start_time
  9. print("Time: ", time_taken)

输出:

  1. Sum: 45
  2. Time: 0.0009975433349609375

8、查找出现次数最多的元素

使用max方法找出列表中出现次数最多的元素。

  1. def most_frequent(list):
  2. return max(set(list), key=list.count)
  3. mylist = [1,1,2,3,4,5,6,6,2,2]
  4. print("出现次数最多的元素是:", most_frequent(mylist))

输出:

出现次数最多的元素是: 2

9、将两个列表转换为字典

有两个列表,将列表A里的元素作为键,将列表B里的对应元素作为值,组成一个字典。

  1. def list_to_dictionary(keys, values):
  2. return dict(zip(keys, values))
  3. list1 = [1, 2, 3]
  4. list2 = ['one', 'two', 'three']
  5. print(list_to_dictionary(list1, list2))

输出:

{1: 'one', 2: 'two', 3: 'three'}

10、异常处理

Python提供了try...except...finally的方式来处理代码异常,当然还有其他组合的方式。

  1. a, b = 1,0
  2. try:
  3. print(a/b)
  4. except ZeroDivisionError:
  5. print("Can not divide by zero")
  6. finally:
  7. print("Executing finally block")
'
运行

输出:

  1. Can not divide by zero
  2. Executing finally block

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/978012
推荐阅读
相关标签
  

闽ICP备14008679号