Python Basics

1. Function

#default values to the functions
def greet(who="Colin"):
    print("Hello,", who)

#make choices in the function
print("Splitting", total_candies, "candy" if total_candies == 1 else "candies")

2. List

#List
primes = [2, 3, 5, 7]#ordered sequences of values.
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']# String in lists
hands = [['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K']]#a list of lists
favourite = [32, 'raindrops on roses', help]#different type of variables

#index
planets[0] #zero-based indexing
planets[-1] #the end of the list can be accessed with negative numbers

#Slicing
planets[0:3]#['Mercury', 'Venus', 'Earth'] but not including index 3
planets[:3] planets[3:] #default left(0) right(length)
planets[1:-1]# All the planets except the first and last
planets[-3:] # The last 3 planets

planets[:3] = ['Mur', 'Vee', 'Ur']#Changing lists
#List Function
len(planets)、sorted(planets)、sum(primes)、max(primes)

#List method /help(planets) to get more
planets.append('Pluto')、planets.pop() #pop will remove the last one and return it
planets.index('Earth')、"Earth" in planets #To avoid unpleasant surprises the first method might occur

3. Loop

#Loop
for planet in planets:
    print(planet, end=' ') # print all on same line
for i in range(5):
    print("Doing important work. i =", i)
while i < 10:
    print(i, end=' ')
    i += 1 # increase the value of i by 1

#List comprehension
squares = [n**2 for n in range(10)] #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
short_planets = [planet for planet in planets if len(planet) < 6] # add an if condition
loud_short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6] #make a change passingly

4. String

claim = "Pluto is a planet!"
planet[0] = 'B'# TypeError   planet.append doesn't work either 
words = claim.split() # ['Pluto', 'is', 'a', 'planet!'] defalt whitespace
year, month, day = datestr.split('-') #datestr = '1956-01-31'
'/'.join([month, day, year]) #  '01/31/1956' 
planet + "string " + str(int) + "string" #str.farmat
"{}, you'll always be the {}th planet to me.".format(planet, position) 

5. Dictionaries

numbers = {'one':1, 'two':2, 'three':3}# the first is the key and the second is its corresponding values
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planet_to_initial = {planet: planet[0] for planet in planets} #initiate a dictionary
planet_to_initial.values() #acess to the values list 
for k in numbers:
      print("{} = {}".format(k, numbers[k])) #k is the key
for planet, initial in planet_to_initial.items():
    print("{} begins with \"{}\"".format(planet.rjust(10), initial)) #acess the key and value simultaneously

6. Other

#Lambda
multiply = lambda x, y: x * y
mean = lambda num_list: sum(num_list)/len(num_list) #lambda function

#Map
averages = list(map(mean, numbers)) # using map() to apply lambda function to a list

#Filter
is_short = lambda name: len(name) < 10
short_cities = list(filter(is_short, cities)) #apply lambda function to select element in list
posted @ 2022-05-27 20:55  失控D大白兔  阅读(25)  评论(0编辑  收藏  举报