The Python code I wrote was well received by my colleagues

Life is short. I use Python.

The goal of a programmer is to become financially free without writing code. No, I accidentally told you the truth, but I should have written the code succinctly and elegantly.

The Python programmer’s quest is Pythonic, which, right in Python, “hides” so many ways to make code simple, elegant, and different.

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

Capitalize the first letter

It’s kind of interesting. I stumbled on it.

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

List of merger

The first way: use +.

>>> a + b
[1.2.3.4.5.6]
Copy the code

The second way: use the extend keyword.

>>> a.extend(b)
>>> a
[1.2.3.4.5.6]
Copy the code

The latter two methods are significantly more elegant and are recommended. One caveat: if the list is large, + is slower and extend is better.

List elements are de-duplicated

Use set() to de-duplicate list elements.

>>> a = [1.2.3.4.2.3]
>>> list(set(a))
[1.2.3.4]
Copy the code

List ordering

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

  1. sort()The method is to operate on the original list, andsorted()Method returns a new list, rather than operating on the original.
  2. sort()Is the method applied to the list, andsorted()You 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 the code

Iterate over the index and element pairs of the list

Use the enumerate() function to output both index and element values.

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

# output
0 python
1 go
2 java
Copy the code

Find the most frequent element in the list

Use the Max () function to quickly find the most frequent 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 the code

It is important to note that when two elements appear in a list the same number of times, the first element is returned.

>>> a = [1.2]
>>> b = max(set(a), key=a.count)
>>> b
1
Copy the code

Counts the number of occurrences of all elements in the list

The previous code shows the values that occur most frequently. If you want to know the number of occurrences of all the elements in a list, you can use the Collections module.

Collections is a treasure trove of Python modules that provide many features. The Counter method fits this requirement perfectly.

>>> 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 the code

Merge the two lists into dictionaries

Using the zip() function, you can combine two lists into dictionaries.

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

Find the intersection of two lists, union and difference

# list_operate.py

def main() :
    list_a = [1.2.3.4.5]
    list_b = [4.5.6.7.8]

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

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

    Two ways of finding the difference set, 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()
Copy the code

Dictionary creation

# 1. Create an empty dictionary
a = {}
b = dict(a)# 2, with initial values, I prefer the second option in terms of ease of input
a = {'a': 1.'b': 2.'c': 3}
b = dict(a=1, b=2, c=3)

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

# 4. Key comes from a list, and value is also a list, using zip
keys = ['a'.'b'.'c']
values = [1.2.3]
d = dict(zip(keys, values))
Copy the code

The dictionary to merge

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

# merge, both ways
# 1. Use update
m.update(n)
# 2. Use **
{**m, **n}
Copy the code

Check whether the key exists

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

Another approach 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 the code

Gets the value in the dictionary

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

If the key does not exist, an error will be reported. Get is recommended
a = d['a']

# 2. Use get and assign a default value if key does not exist
a = d.get('a')
c = d.get('c'.3)
Copy the code

The dictionary traversal

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

# traverse the key
for key in d.keys():
    pass

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

Pass through key and value
for key, value in d.items():
    pass
Copy the code

Dictionary derivation

List and dictionary derivations are one of my favorite features, they’re very concise and efficient. I’m almost out of map and Filter.

l = [1.2.3]
{n: n * n for n in l}
{1: 1.2: 4.3: 9}
Copy the code

Dictionaries are 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])
# in 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])
Copy the code

Another requirement THAT I often encounter during development is to have a list, the elements of the list are dictionaries, and then sort the list 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
sorted(l, key=lambda e: e.__getitem__('count'), reverse=True)
Copy the code

The above is the content of this article, if you feel good, welcome to like, forward and follow, thank you for your support.


Recommended reading:

  • Go Learning Route (2022)
  • Learning Python (2022)