How many of the 12 basic Python grammars do you know?

Nova project It was included in two columns at the same time
8 articles 1 subscription
35 articles 143 subscriptions

preface

I wrote an article about Python advanced syntax a few days ago,Bronze to the king, these Python skills will be used

A reader's private letter said: how do you think you're getting started with Python? What are the basic Python syntax in development?

The following 12 small cases contain very practical syntax in daily development. Let's test how many do you know?

1. Multiple strings are combined into one string

list_ of_ strings = ['My', 'name', 'is', 'Dragon']

# Using join with the comma separator
print(' '.join(list_of_strings))

# Output
# My name is Dragon

2. Split string into substring list

string_ one= "My name is Dragon"
string_ two= "sample/ string 2"

# default separator ' '
print(string_1.split())
# ['My', 'name', 'is', 'Dragon']

# defining separator as '/'
print(string_2.split('/'))
# ['sample', ' string 2']

3. Count the number of elements in the list

# finding frequency of each element in a list
fromcollections importCounter

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(one)) # most frequent element
# [('d', 5)]

4. Use the try except else block module

a,b = one,0

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

# output
# division by zero
# Run this always

5. Use the enumeration function to get the key / value pair

my_ list = ['a', 'b', 'c', 'd', 'e']

forindex,value in enumerate(my_list):
    print('{0}: {1}'.format(index,value))

# 0: a
# 1: b
# 2: c
# 3: d
# 4: e

6. Check the memory usage of the object

importsys
num = twenty-one
print(sys.getsizeof(num))
# In Python 3, 28

7. Merge Dictionaries

dict_ one= {'apple': nine, 'banana': six}
dict_ two= {'banana': four, 'orange': eight}

combined_ dict = {**dict_1, **dict_2}

print(combined_dict)
# Output
# {'apple': 9, 'banana': 4, 'orange': 8}

8. Calculate the time spent executing a piece of code

importtime

start_ time =time.time()
# Code to check follows
fori in range(ten**five):
a,b = one,two
c =a+b
# Code to check ends
end_ time =time.time()
time_ taken_ in_ micro = (end_time-start_time)*(ten**six)

print(time_taken_in_micro)

# output
# 28770.217895507812

9. List expansion

fromiteration_ utilities importdeepflatten

# if you only have one depth nested_ list, use this
def flatten(l):
  return [item forsublist inl foritem insublist]

l = [[one,two,three],[three]]
print(flatten(l))
# [1, 2, 3, 3]

# if you don't know how deep the list is nested
l = [[one,two,three],[four,[five],[six,seven]],[eight,[nine,[ten]]]]

print(list(deepflatten(l,depth=three)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

10. List sampling

importrandom

my_ list = ['a', 'b', 'c', 'd', 'e']
num_ samples = two

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

11. Digitization

num = one hundred and twenty-three thousand four hundred and fifty-six

# using map
list_ 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) forx in str(num)]

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

12. Check the uniqueness of list elements

def unique(l):
    if len(l)==len(set(l)):
        print("All elements are unique")
    else:
        print("List has duplicates")

unique([one,two,three,four])
# All elements are unique

unique([one,one,two,three])
# List has duplicates
emoticon
Insert expression
©️ 2020 CSDN Skin theme: swimming - white Designer: Bai Songlin Return to home page
Paid inelement
Payment with balance
Click retrieve
Code scanning payment
Wallet balance 0

Deduction Description:

1. The balance is the virtual currency of wallet recharge, and the payment amount is deducted according to the ratio of 1:1.
2. The balance cannot be purchased and downloaded directly. You can buy VIP, c-coin package, paid column and courses.

Balance recharge