Python 总结

[TOC]

将两个list转换为dictionary

# 将两个list转换为dictionary
list_1 = ['karl', 'lay', 'martin']
list_2 = [111, 222, 333]

# Method 1 : zip()
dict_1 = dict(zip(list_1, list_2))

# Method 2 : dictionary comprehension
dict_2 = {key: value for key, value in zip(list_1, list_2)}

# Method 3 : Using a For loop (Not Recommended)
tuples = zip(list_1, list_2)
dict_3 = {}
for key, value in tuples:
if key in dict_3:
pass
else:
dict_3[key] = value
print(dict_1, dict_2, dict_3, sep= "\n")

""" Output
{'karl': 111, 'lay': 222, 'martin': 333}
{'karl': 111, 'lay': 222, 'martin': 333}
{'karl': 111, 'lay': 222, 'martin': 333}
"""

对字符串列表进行排序

# 对字符串列表进行排序
list1 = ["Karl","Larry","Ana","Zack"]

# sort是在原位重新排列列表,而sorted ()是产生一个新的列表。
# sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。

# Method 1: sort()
list1.sort()

# Method 2: sorted()
sorted_list = sorted(list1)

# Method 3: Brute Force Method
size = len(list1)
for i in range(size):
for j in range(size):
if list1[i] < list1[j]:
temp = list1[i]
list1[i] = list1[j]
list1[j] = temp

print(list1)
""" Output
['Ana', 'Karl', 'Larry', 'Zack']
"""

List Comprehension with if and else

## List Comprehension with if and else

list_1 = ["Divided By 5" if i%5 == 0 else i for i in range(1, 20)]
list_2 = ["FizzBuzz" if i%3 == 0 and i%5 == 0 else 'Fuzz' if i%3 == 0 else 'Buzz' if i%5 == 0 else i for i in range(1, 20)]

print(list_1, list_2, sep="\n")
""" Output
[1, 2, 3, 4, 'Divided By 5', 6, 7, 8, 9, 'Divided By 5', 11, 12, 13, 14, 'Divided By 5', 16, 17, 18, 19]
[1, 2, 'Fuzz', 4, 'Buzz', 'Fuzz', 7, 8, 'Fuzz', 'Buzz', 11, 'Fuzz', 13, 14, 'FizzBuzz', 16, 17, 'Fuzz', 19]
"""

添加来自两个列表的元素

# 添加来自两个列表的元素

maths = [59, 64, 75, 86]
physics = [78, 98, 56, 56]

# Brute Force Method
list1 = [
maths[0]+physics[0],
maths[1]+physics[1],
maths[2]+physics[2],
maths[3]+physics[3]
]

# List Comprehension
list1 = [x + y for x,y in zip(maths,physics)]

# Using Maps
import operator
all_devices = list(map(operator.add, maths, physics))

# Using Numpy Library
import numpy as np
list1 = np.add(maths,physics)

print(list1)

'''Output
[137 162 131 142]
'''

对dictionary列表进行排序

dict1 = [
{"Name":"Karl",
"Age":25},
{"Name":"Lary",
"Age":39},
{"Name":"Nina",
"Age":35}
]

## Using sort()
dict1.sort(key=lambda item: item.get("Age"))

# List sorting using itemgetter
from operator import itemgetter
f = itemgetter('Name')
dict1.sort(key=f)

# Iterable sorted function
dict1 = sorted(dict1, key=lambda item: item.get("Age"))

print(dict1)
'''Output
[{'Age': 25, 'Name': 'Karl'},
{'Age': 35, 'Name': 'Nina'},
{'Age': 39, 'Name': 'Lary'}]
'''

检查字符串中的子字符串

addresses = [
"12/45 Elm street",
'34/56 Clark street',
'56,77 maple street',
'17/45 Elm street'
]

street = 'Elm street'

for i in addresses:
if street in i:
print(i)

'''output
12/45 Elm street
17/45 Elm street
'''

字符串格式

name = "Abhay"
age = 21

# METHOD 1: Concatenation
print("My name is " + name + ", and I am " + str(age) + " years old.")

# METHOD 2: F-strings (Python 3+)
print(f"My name is {name}, and I am {age} years old")

# METHOD 3: Join
print(''.join(["My name is ", name, ", and I am ", str(age), " years old"]))

# METHOD 4: modulus operator
print("My name is %s, and I am %d years old." % (name, age))

# METHOD 5: format(Python 2 and 3)
print("My name is {}, and I am {} years old".format(name, age))

""" Output
My name is Abhay, and I am 21 years old.
My name is Abhay, and I am 21 years old
My name is Abhay, and I am 21 years old
My name is Abhay, and I am 21 years old.
My name is Abhay, and I am 21 years old
"""

列表中最常见的元素

# 列表中最常见的元素
def most_frequent(nums):
return max(set(nums), key = nums.count)

list = [0, 1, 2, 1, 4, 5]
most_frequent_num = most_frequent(list)

print(most_frequent_num)
""" Output
1
"""

在没有if-else情况下计算

import operator
action = {
"+" : operator.add,
"-" : operator.sub,
"/" : operator.truediv,
"*" : operator.mul,
"**" : pow
}
print(action['*'](5, 5)) # 25

Chained Function调用

# 在python中,你可以在同一行代码调用多个函数。
def add(a,b):
return a+b

def sub(a,b):
return a-b

a,b = 9,6
print((sub if a > b else add)(a, b))

交换数值

a,b = 5,7

# Method 1
b,a = a,b

# Method 2
def swap(a,b):
return b,a

swap(a,b)

print(a,b)
""" Output
7 5
"""

查找重复项

def has_duplicates(lst):
return not len(lst) == len(set(lst))

x = [1, 2, 2, 4, 3, 5]
y = [1, 2, 3, 4, 5]

print(has_duplicates(x)) # True
print(has_duplicates(y)) # True

在给定范围内,算所有数的平方

# METHOD 1
from itertools import repeat
n = 5
squares = list(map(pow, range(1, n+1), repeat(2)))
print(squares)

# METHOD 2
n = 6
squares = [i**2 for i in range(1,n+1)]
print(squares)

"""Output
[1, 4, 9, 16, 25]
"""

合并两个字典

basic_information = {"name":['karl','Lary'],"mobile":["0134567894","0123456789"]}
academic_information = {"grade":["A","B"]}

details = dict() ## Combines Dict

## Dictionary Comprehension Method
details = {key: value for data in (basic_information, academic_information) for key,value in data.items()}
print(details)

## Dictionary unpacking
details = {**basic_information ,**academic_information}
print(details)

## Copy and Update Method
details = basic_information.copy()
details.update(academic_information)
print(details)