10-tips-for-python

pyt编程中的10个小技巧

GPL-3.0 License

Stars
7

Python10

Tips1

tmp

a = 1;b = 2

tmp = a;a = b;b = tmp

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

a, b = b, a

print(a,b)

**** 2,1

Tips2

name = "JohnserfSeed";country = "China";age = 19
print("Hi, I'm " + name + ". I'm from " + country + ". And I'm " + str(age) + ".")

**** Hi, I'm JohnserfSeed. I'm from China. And I'm 19.

f-stringformat

print("Hi, I'm %s. I'm from %s. And I'm %d." % (name,country,age))

print("Hi, I'm {}. I'm from {}. And I'm {}.".format(name,country,age))

print("Hi, I'm {0}. Yes, I'm {0}!".format(name))

#pytv > 3.6
print(f"Hi, I'm {name}. I'm from {country}. And I'm {age}.")    #f-string   {age + 1} 20 {age()}

f-stringpyt3.6


Hi, I'm JohnserfSeed. I'm from China. And I'm 19. Hi, I'm JohnserfSeed. I'm from China. And I'm 19. Hi, I'm JohnserfSeed. Yes, I'm JohnserfSeed! Hi, I'm JohnserfSeed. I'm from China. And I'm 19.

Tips3 yield

def fibonacci(n):
    """
    param :n = n
    return:
    """
    a = 0;b = 1
    nums = []
    for _ in range(n):
        nums.append(a)
        a, b = b ,a + b    
    return nums

for i in fibonacci(10):
    print(i)
def fibonacci(n):
    """
    param :n = n
    return:
    """
    a = 0;b = 1
    for _ in range(n):
        yield a	#yield
        a, b = b ,a + b    

for i in fibonacci(10):
    print(i)

yield (generator), yield a fibonacci yield a


0 1 1 2 3 5 8 13 21 34

Tips4

fruit = ["apple","pear","pineapple","orange","banana"]

a

filtered_fruit = []
for f in fruit:
    if f.startswith("a"):
        filtered_fruit.append(f)
        
print(filtered_fruit)
filtered_fruit = [x for x in fruit if x.startswith("a")]

print(filtered_fruit)

fruit

**** ['apple']

for i in range(len(fruit)):
    fruit[i] = fruit[i].upper()
    
print(fruit)
fruit = [x.upper() for x in fruit]

print(fruit)

**** ['APPLE', 'PEAR', 'PINEAPPLE', 'ORANGE', 'BANANA']

Tips5 enumerate

fruitforpytenumerate()

for i,x in enumerate(fruit):
    print(i,x)

0 APPLE 1 PEAR 2 PINEAPPLE 3 ORANGE 4 BANANA

Tips6

fruitreversed(),a~zpytsorted()

#fruit
for i,x in enumerate(reversed(fruit)):
    print(i,x)

#a~z
for i,x in enumerate(sorted(fruit)):
    print(i,x)

0 BANANA 1 ORANGE 2 PINEAPPLE 3 PEAR 4 APPLE

0 APPLE 1 BANANA 2 ORANGE 3 PEAR 4 PINEAPPLE

Tips7

a = {"rose": "123456", "xiaoming": "abc123"}
b = {"lilei": "111111", "zhangsan": "12345678"}

abc[]

c = {}
for k in a:
    c[k] = a[k]
for k in b:
    c[k] = b[k]

print(c)

(unpacking),

c = {**a, **b}  #**

print(c)

pyt**

**** {'rose': '123456', 'xiaoming': 'abc123', 'lilei': '111111', 'zhangsan': '12345678'}

Tips8

if...else...

if score > 60:
    s = "pass"
else:
    s = "fail"
    
print(s)

;

s = "pass" if score > 60 else "fail"    # s = "pass"  s ="fail"

print(s)

Tips9

split()

#

name = "Johnserf Seed"

str_list = name.split()
first_name = str_list[0]
last_name = str_list[1]

print(first_name,last_name)
first_name, last_name = name.split()    #

print(first_name,last_name)

**** Johnserf Seed

Tips10 with

pytopen()

#

f = open("somefile.txt", "r")
s = f.read()
f.close()   #

print(s)

with open()

with open("somefile.txt", "r") as f:
    s = f.read()

print(s)

somefile


..\1.txt ..\2.img ..\3.mp4

10-tips-for-python

10