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

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: use the extendkeyword .

>>> 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, it +will be slower and extendbetter .

List element deduplication

set()Use to deduplicate list elements.

>>> a = [1, 2, 3, 4, 2, 3]
>>> list(set(a))
[1, 2, 3, 4]
复制代码

Sort the list

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

  1. sort()The method operates on the original list, and the sorted()method returns a new list, not on the original basis.
  2. sort()is a method applied to lists, and sorted()can perform sorting operations 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

Use the enumerate()function to 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

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
复制代码

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

Using the zip()function , two lists can be combined 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]

    # 求交集的两种方式
    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()
复制代码

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))
复制代码

dictionary merge

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

# 合并,两种方式
# 1、使用 update
m.update(n)
# 2、使用 **
{**m, **n}
复制代码

Determine whether the key exists

In Python2, it can be used to determine whether a key exists, has_keybut this method has been removed in Python3.

Another way is to use the inkeyword , 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')    
复制代码

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)
复制代码

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
复制代码

dictionary comprehension

List comprehensions and dictionary comprehensions are my favorite features, concise and efficient. mapAnd filterI'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}

# 按 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])
复制代码

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'))
# 倒序
sorted(l, key=lambda e: e.__getitem__('count'), reverse=True)
复制代码

The above is the whole content of this article. If you think it is not bad, please like , forward and follow , thank you for your support.


Recommended reading:

Guess you like

Origin juejin.im/post/7078284540745089055