Python programming language skills sharing

Here are some Python programming language tips:

  1. Use List Comprehension to build new lists to avoid loops and list appends.

For example, to square all elements in a list:

original_list = [1, 2, 3, 4, 5]
squared_list = [x ** 2 for x in original_list]

  1. Use lambda expressions to define simple anonymous functions.

For example, define a function that adds two numbers:

sum = lambda x, y: x + y
print(sum(2, 3))

  1. The difference between Deep Copy and Shallow Copy.

In Python, when using the copy() method to copy, there are two methods: deep copy and shallow copy. A shallow copy only copies a reference to an object, while a deep copy copies the entire object and its nested objects.

  1. Use the enumerate() function to get the index and element.

For example, to print out all elements in a list and their indices:

my_list = ['apple', 'banana', 'orange']
for index, value in enumerate(my_list):
    print(index, value)

  1. Use the zip() function to combine two lists into a dictionary.

For example, combine elements from two lists into a dictionary:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))
print(my_dict)

  1. Use the Counter class in the collections module to count the number of times an element appears.

For example, count the number of occurrences of each element in a list:

from collections import Counter

my_list = [1, 2, 3, 1, 2, 1, 3, 1, 2, 3]
my_counter = Counter(my_list)
print(my_counter)

  1. Use the join() method to concatenate a list of strings into a single string.

For example, to concatenate all elements in a list of strings into a single string:

my_list = ['Hello', 'World']
my_string = ' '.join(my_list)
print(my_string)

Reprinted from: Weidian Reading    https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/hdxx2022/article/details/132651057