Home > Backend Development > Python Tutorial > The Python code I wrote was praised by my colleagues.

The Python code I wrote was praised by my colleagues.

王林
Release: 2023-04-12 13:43:12
forward
1236 people have browsed it

Life is short, I use Python.

The pursuit of programmers is to achieve financial freedom as soon as possible without writing code. No, I accidentally told the truth. I should have written the code concisely and elegantly.

The pursuit of Python programmers is Pythonic. Just in the language of Python, there are many "hidden" methods that can make the code concise, elegant, and unique.

I have summarized some common operations here, especially regarding lists and dictionaries, to share with you.

The first letter is capitalized

This method is a bit interesting, I discovered it accidentally.

>>> s = "programming is awesome"
>>> print(s.title())
Programming Is Awesome
Copy after login

List merge

The first way: use .

>>> a + b
[1, 2, 3, 4, 5, 6]
Copy after login

The second way: use the extend keyword.

>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
Copy after login

The latter two methods are obviously more elegant and are recommended. One thing to note is that if the list is large, it will be slower and it is better to use extend.

Deduplication of list elements

Use set() to deduplicate list elements.

>>> a = [1, 2, 3, 4, 2, 3]
>>> list(set(a))
[1, 2, 3, 4]
Copy after login

List sorting

Use sort() or the built-in function sorted() to sort the list. There are two differences between them: the

  • sort() method operates on the original list, while the sorted() method returns a new list, rather than operating on the original basis.
  • sort() is a method applied to lists, while sorted() can sort all iterable objects.
# sort()
>>> a = [1, 2, 3, 4, 2, 3]
>>> a.sort()
>>> a
[1, 2, 2, 3, 3, 4]
>>>
>>> a = [1, 2, 3, 4, 2, 3]
>>> a.sort(reverse=True)
>>> a
[4, 3, 3, 2, 2, 1]

# sorted()
>>> a = [1, 2, 3, 4, 2, 3]
>>> sorted(a)
[1, 2, 2, 3, 3, 4]
>>> a = [1, 2, 3, 4, 2, 3]
>>> sorted(a, reverse=True)
[4, 3, 3, 2, 2, 1]
Copy after login

Traverse the index and element pairs of the list

Use the enumerate() function to output the index and element value at the same time.

>>> a = ['python', 'go', 'java']
>>> for i, v in enumerate(a):
... print(i, v)

# output
0 python
1 go
2 java
Copy after login

Find the most frequently occurring element in a list

Use the max() function to quickly find the most frequently occurring element in a list.

>>> a = [1, 2, 3, 4, 3, 4, 5, 4, 4, 2]
>>> b = max(set(a), key=a.count)
>>> b
4
Copy after login

One thing to note is that when two elements appear the same number of times in the list, the first element that appears will be returned.

>>> a = [1, 2]
>>> b = max(set(a), key=a.count)
>>> b
1
Copy after login

Count the occurrences of all elements in the list

The previous code gives the most frequently occurring value. If you want to know the number of occurrences of all elements in a list, you can use the collections module.

collections is a treasure module in Python that provides a lot of features. The Counter method can perfectly solve this requirement.

>>> from collections import Counter
>>>
>>> a = [1, 2, 3, 4, 3, 4, 5, 4, 4, 2]
>>> Counter(a)
Counter({4: 4, 2: 2, 3: 2, 1: 1, 5: 1})
Copy after login

Merge two lists into a dictionary

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

>>> a = ['one', 'tow', 'three']
>>> b = [1, 2, 3]
>>> dict(zip(a, b))
{'one': 1, 'tow': 2, 'three': 3}
Copy after login

Find the intersection, union and difference of two lists.

# list_operate.py

def main():
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]

# 求交集的两种方式
res_a = [i for i in list_a if i in list_b]
res_b = list(set(list_a).intersection(set(list_b)))

print(f"res_a is: {res_a}")
print(f"res_b is: {res_b}")

# 求并集
res_c = list(set(list_a).union(set(list_b)))
print(f"res_c is: {res_c}")

# 求差集的两种方式,在B中但不在A中
res_d = [i for i in list_b if i not in list_a]
res_e = list(set(list_b).difference(set(list_a)))

print(f"res_d is: {res_d}")
print(f"res_e is: {res_e}")


if __name__ == '__main__':
main()
Copy after login

Dictionary creation

# 1、创建空字典
a = {}
b = dict()

# 2、有初始值,从输入的便利程度来说,我更喜欢第二种
a = {'a': 1, 'b': 2, 'c': 3}
b = dict(a=1, b=2, c=3)

# 3、key 来自一个列表,而 value 相同, 使用 fromkeys,那是相当的优雅
keys = ['a', 'b', 'c']
value = 100
d = dict.fromkeys(keys, value)

# 4、key 来自一个列表,而 value 也是一个列表,使用 zip
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))
Copy after login

Dictionary merging

m = {'a': 1}
n = {'b': 2, 'c': 3}

# 合并,两种方式
# 1、使用 update
m.update(n)
# 2、使用 **
{**m, **n}
Copy after login

Judge whether a key exists

To determine whether a key exists in Python2, you can use has_key, but This method has been removed in Python3.

Another method is to use the in keyword, which is not only compatible with Python2 and Python3, but also faster and highly recommended.

d = {'a': 1, 'b': 2}
if 'a' in d:
print('hello')
Copy after login

Get the value in the dictionary

d = {'a': 1, 'b': 2}

# 1、直接用 key 取值,但这种方式不好,如果 key 不存在会报错,推荐使用 get
a = d['a']

# 2、使用 get,如果 key 不存在还可以赋默认值
a = d.get('a')
c = d.get('c', 3)
Copy after login

Dictionary traversal

d = {'a': 1, 'b': 2, 'c': 3}

# 遍历 key
for key in d.keys():
pass

# 遍历 value
for value in d.values():
pass

# 遍历 key 和 value
for key, value in d.items():
pass
Copy after login

Dictionary comprehension

List comprehension and dictionary comprehension are my favorite features , simple and efficient. I can barely use map and filter anymore.

l = [1, 2, 3]
{n: n * n for n in l}
{1: 1, 2: 4, 3: 9}
Copy after login

Dictionaries are sorted by key or value

d = {'a': 1, 'b': 2, 'e': 9, 'c': 5, 'd': 7}

# 按 key 排序
sorted(d.items(), key=lambda t: t[0])
# 按 key 倒序
sorted(d.items(), key=lambda t: t[0], reverse=True)

# 按 value 排序
sorted(d.items(), key=lambda t: t[1])
Copy after login

There is another requirement that I often encounter during the development process, which is to have a list, the elements of the list are dictionaries, and then sort them by the value of the dictionary Sort the list.

l = [{'name': 'a', 'count': 4}, {'name': 'b', 'count': 1}, {'name': 'd', 'count': 2}, {'name': 'c', 'count': 6}]
sorted(l, key=lambda e: e.__getitem__('count'))
# 倒序
sorted(l, key=lambda e: e.__getitem__('count'), reverse=True)
Copy after login

The above is the detailed content of The Python code I wrote was praised by my colleagues.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template