20 of Python code, you need to immediately learn, easy to cry!

BS is a non-Python programming language. Design simplicity and legibility it is popular for two reasons. As the purpose of Python: Beautiful is better than ugly, implicit rather than explicit.

Remember some help to improve the design of common coding tips are useful. At the necessary time, these tips can reduce your Internet search Stack Overflow trouble. And they will help you in your daily exercise program.

1, reversing a string

The following code uses the Python inverts slicing string.

# Reversing a string using slicing
my_string = "ABCDE"reversed_string = my_string[::-1]
print(reversed_string)
# Output# EDCBA

2, using the class title (capitalized)

The following code can be used to convert a string class title. This is accomplished by using the string class title () method.

my_string = "my name is chaitanya baweja"
# using the title() function of string classnew_string = my_string.title()
print(new_string)
# Output# My Name Is Chaitanya Baweja

 

3, the search string only factor

The following code can be used to find all the unique elements of the string. We use its properties, all the elements of a string which is unique.

my_string = "aavvccccddddeee"
# converting the string to a settemp_set = set(my_string)
# stitching set into a string using joinnew_string = ''.join(temp_set)
print(new_string)

 

4, the n-th output string or list

You can use the multiplication of string or list (*). Thus, any of them may be doubled on demand.

n = 3 # number of repetitions
my_string = "abcd"
my_list = [1,2,3]

print(my_string*n)
# abcdabcdabcd
print(my_list*n)# [1,2,3,1,2,3,1,2,3]import streamlit as st

 

An interesting use case is to define a constant having a value list, assumed to be zero.

n = 4my_list = [0]*n # n denotes the length of the required list# [0, 0, 0, 0]

 

5, list comprehension

On the basis of the other lists, list comprehensions provide an elegant way to create the list.

The following code twice by multiplying each object old list, create a new list.

# Multiplying each element in a list by 2
original_list = [1,2,3,4]
new_list = [2*x for x in original_list]
print(new_list)# [2,4,6,8]

 

6, the value of the exchange between the two variables

Python can be very simple exchange value between two variables, without the use of a third variable.

a = 1b = 2
a, b = b, a
print(a) # 2print(b) # 1

 

7, split into sub-string string list

By using .split () method, the string may be divided into sub-list of strings. You may also want to split delimiter passed as a parameter.

string_1 = "My name is Chaitanya Baweja"string_2 = "sample/ string 2"
# default separator ' 'print(string_1.split())# ['My', 'name', 'is', 'Chaitanya', 'Baweja']
# defining separator as '/'print(string_2.split('/'))# ['sample', ' string 2']

 

8, the integrated list of strings into a single string

join () method to integrate the list of strings into a single string. In the following example, a comma separators to separate them.

list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
# Using join with the comma separatorprint(','.join(list_of_strings))
# Output# My,name,is,Chaitanya,Baweja

 

9, checks whether or not a given string is a palindrome (Palindrome)

Reverse text has been discussed above. Therefore, the palindrome become a simple program in Python.

my_string = "abcba"
m if my_string == my_string[::-1]:    print("palindrome")else:    print("not palindrome")
# Output# palindrome

 

10, a list of elements of frequency

There are many ways to accomplish this task, and I like to use Python's Counter class. Python counter to track the frequency of each element, Counter () is fed back to a dictionary, which is a key element, the frequency is the value.

Also use most_common () function to get most_frequent element in the list.

# finding frequency of each element in a listfrom collections import Counter
my_list = ['a','a','b','b','b','c','d','d','d','d','d']count = Counter(my_list) # defining a counter object
print(count) # Of all elements# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
print(count['b']) # of individual element# 3
print(count.most_common(1)) # most frequent element# [('d', 5)]

 

11, to find whether two strings anagrams

An interesting application of the Counter class is to find anagrams.

anagrams letter refers to the different words or the words reorder new words or new words constituted.

If the counter object is two strings are equal, that they are anagrams.

From collections import Counter
str_1, str_2, str_3 = "acbde", "abced", "abcda"cnt_1, cnt_2, cnt_3  = Counter(str_1), Counter(str_2), Counter(str_3)
if cnt_1 == cnt_2:    print('1 and 2 anagram')if cnt_1 == cnt_3:    print('1 and 3 anagram')

 

12, a try-except-else block

It is easily solved by using try / except block, Python error handling. Add else statements in the block may be useful. When no abnormality in the try block, the normal operation.

If you want to run certain programs, use finally, regardless of anomalies.

a, b = 1,0
try:    print(a/b)    # exception raised when b is 0except ZeroDivisionError:    print("division by zero")else:    print("no exceptions raised")finally:    print("Run this always")

 

13, include the use of indexes and values ​​acquired

The following script uses the list to iterate the value of its index in the list.

my_list = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(my_list):    print('{0}: {1}'.format(index, value))
# 0: a# 1: b# 2: c# 3: d# 4: e

 

14, the memory usage of the object under examination

The following script can be used to check memory usage object.

import sys
num = 21
print(sys.getsizeof(num))
# In Python 2, 24# In Python 3, 28

 

15, merge two dictionaries

In In Python 2, using the update () method of merging two dictionaries, and Python3.5 make the operations easier.

In the given script to merge two dictionaries. We used the dictionary of the second value, in order to avoid cross-case situation.

dict_1 = {'apple': 9, 'banana': 6}
dict_2 = {'banana': 4, 'orange': 8}
combined_dict = {**dict_1, **dict_2}
print(combined_dict)# Output# {'apple': 9, 'banana': 4, 'orange': 8}

 

16, the time required for implementation of a code

The following code uses a software library computing time a piece of code execution time spent.

import time

start_time = time.time()# Code to check followsa, b = 1,2c = a+ b# Code to check endsend_time = time.time()time_taken_in_micro = (end_time- start_time)*(10**6)
print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)

 

17, a list of inventory flat

Sometimes nesting depth you are unsure of the list, and just all of the elements in a single plane list.

Can be obtained in the following ways:

from iteration_utilities import deepflatten
# if you only have one depth nested_list, use thisdef flatten(l):  return [item for sublist in l for item in sublist]
l = [[1,2,3],[3]]print(flatten(l))# [1, 2, 3, 3]
# if you don't know how deep the list is nestedl = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
print(list(deepflatten(l, depth=3)))# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 

若有正确格式化的数组,Numpy扁平化是更佳选择。

18、 列表取样

通过使用random软件库,以下代码从给定的列表中生成了n个随机样本。

import random

my_list = ['a', 'b', 'c', 'd', 'e']num_samples = 2
samples = random.sample(my_list,num_samples)print(samples)# [ 'a', 'e'] this will have any 2 random values

 

强烈推荐使用secrets软件库生成用于加密的随机样本。

以下代码仅限用于Python 3。

import secrets                              # imports secure module.secure_random = secrets.SystemRandom()      # creates a secure random object.
my_list = ['a','b','c','d','e']num_samples = 2
samples = secure_random.sample(my_list, num_samples)
print(samples)# [ 'e', 'd'] this will have any 2 random values

 

19、数字化

以下代码将一个整数转换为数字列表。

num = 123456
# using maplist_of_digits = list(map(int, str(num)))
print(list_of_digits)
# [1, 2, 3, 4, 5, 6]

# using list comprehension
list_of_digits = [int(x) for x in str(num)]

print(list_of_digits)# [1, 2, 3, 4, 5, 6]

 

20、 检查唯一性

以下函数将检查一个列表中的所有要素是否唯一。

def unique(l):
    if len(l)==len(set(l)):        print("All elements are unique")    else:        print("List has duplicates")
unique([1,2,3,4])# All elements are unique
unique([1,1,2,3])# List has duplicates
#在学习Python的过程中,往往因为没有资料或者没人指导从而导致自己不想学下去了,因此我特意准备了个群 592539176 ,群里有大量的PDF书籍、教程都给大家免费使用!不管是学习到哪个阶段的小伙伴都可以获取到自己相对应的资料!

 

Guess you like

Origin www.cnblogs.com/chengxyuan/p/11950528.html