The Python code I wrote, my colleagues said it was good

Time:2022-8-5

Original link: The Python code I wrote, my colleagues said it was good

Life is short, I use Python.

The pursuit of programmers is not to write code, and financial freedom as soon as possible. No, I accidentally told the truth, the code should be written concisely and elegantly.

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

Here I summarize some common operations, especially about lists and dictionaries, and share them with you.

Capitalize the first letter

This method is a bit interesting, I discovered it by accident.

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

list merge

The first way: use+

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

The second way: useextendkeywords.

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

The latter two methods are significantly more elegant and are recommended. One thing to note is that if the list is large,+will be slower, useextendbetter.

List element deduplication

useset()Deduplicate list elements.

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

Sort the list

usesort()or built-in functionssorted()Sort the list. There are two differences between them:

  1. sort()The method is to operate on the original list, andsorted()The method returns a new list instead of operating on the original.
  2. sort()is a method applied to a list, andsorted()Sorting operations can be performed on 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]

Iterate over the index and element pairs of a list

useenumerate()The function can output both the index and the element value.

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

# output
0 python
1 go
2 java

Find the most frequent element in a list

usemax()The function can quickly find an element that occurs most frequently in a list.

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

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

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

Count occurrences of all elements in a list

The preceding 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 trove module in Python that provides a lot of features.CounterThis method can perfectly solve this need.

>>> 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})

Merge two lists into a dictionary

usezip()function to combine two lists into a dictionary.

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

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]

    # Two ways to find intersection
    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}")

    # find the union
    res_c = list(set(list_a).union(set(list_b)))
    print(f"res_c is: {res_c}")

    # Two ways to find the difference, in B but not in 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()

dictionary creation

# 1. Create an empty dictionary
a = {}
b = dict()

# 2. There is an initial value. From the convenience of input, I prefer the second
a = {'a': 1, 'b': 2, 'c': 3}
b = dict(a=1, b=2, c=3)

# 3. The key comes from a list, and the value is the same. Using fromkeys is quite elegant
keys = ['a', 'b', 'c']
value = 100
d = dict.fromkeys(keys, value)

# 4, key comes from a list, and value is also a list, use zip
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))

dictionary merge

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

# Merge, two ways
# 1. Use update
m.update(n)
# 2. Use**
{**m, **n}

Determine whether the key exists

To determine whether a key exists in Python2, you can usehas_key, but this method has been removed in Python 3.

Another way is to useinkeyword, not only compatible with Python2 and Python3, but also faster, highly recommended.

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

get the value in the dictionary

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

# 1. Use the key to get the value directly, but this method is not good. If the key does not exist, an error will be reported. It is recommended to use get
a = d['a']

# 2. Use get, if the key does not exist, you can also assign the default value
a = d.get('a')
c = d.get('c', 3)

dictionary traversal

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

# iterate over keys
for key in d.keys():
    pass

# iterate over the value
for value in d.values():
    pass

# iterate over keys 和 value
for key, value in d.items():
    pass

dictionary comprehension

List comprehensions and dictionary comprehensions are my favorite features, concise and efficient.mapandfilterI'm almost out of use.

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

Dictionary sorted by key or value

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

# sort by key
sorted(d.items(), key=lambda t: t[0])
# Reverse order by key
sorted(d.items(), key=lambda t: t[0], reverse=True)

# sort by value
sorted(d.items(), key=lambda t: t[1])

There is also a requirement that I often encounter in the development process, that is, there is a list, the elements of the list are dictionaries, and then the list is sorted by the value of the dictionary.

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'))
# reverse order
sorted(l, key=lambda e: e.__getitem__('count'), reverse=True)

The above is the whole content of this article, if you think it is good, welcomelikeForwardandfocus on,Thanks for the support.


Recommended reading:

Recommended Today

gRPC, great praise

Original link:gRPC, great praise The gRPC technology is really great, with strict interface constraints and high performance. It is used in k8s and many microservice frameworks. As a programmer, learn it right. I have written some gRPC services in Python before, and now I am going to use Go to experience the authentic gRPC program […]