Python Foundation - Lists, Tuples, Dictionaries, Strings

Keywords: Python Google less

Multidimensional array

nums1 = [1,2,3] #One-dimensional array
nums2 = [1,2,3,[4,56]] #Two-dimensional array
nums3 = [1,2,3,4,['a','b','c','d','e',['One','Two','Three']],['Four','Five']] #Three dimensional array
nums4 = [1,2,3,4,['a','b','c','d','e',['One','Two','Three',[1,2,3]]]] #Four dimensional array
print(nums2[3][1]) #56
print(nums2[-1][-1]) #56
print(nums3[4][5][1]) #'two'
print(nums3[5][1]) #'five'
print(nums3[-1][-1]) #'five'

list

Different types of values can be placed in the list, and the subscript of the list starts at 0.

#Define a list
stu_name = ['Zhang San', 'Li Si', 'Wang Wu', 1, 1.5]
print(stu_name) #Print all the contents of the list
print(stu_name[0]) #Print'Zhang San'
len()

length = len(stu_name) #The length of the list, the number of elements in the list 

list adds elements

append()
insert()

stu_name.append('Zhu Liu') #Add an element at the end of the list
stu_name.insert(0, 'Small army') #Insert an element at the specified location
print(stu_name)

list modification element

stu_name[6] = 'Spade shovel'
print(stu_name)

list deletion element

pop()
remove()
del
reverse()

stu_name.pop() #Delete the last element
stu_name.pop(4) #Delete the specified subscript element
stu_name.remove('Small army') #Delete the specified element, having multiple identical elements, and delete the first
del stu_name[-1] #Delete the element at the specified position, with the positive beginning in positive order and the negative beginning in reverse order.
print(stu_name)

list lookup element

count()
index()
reverse()
clear()

my_list = ['Small black', 'Xiao Bai', 1, 1, 2, 1.5]
print(my_list[-1])
print(my_list[0])
print(my_list.count(1)) #Query the number of times an element appears in a list
print(my_list.index(1)) #Find the subscript of the element, take the first of many identical elements, and the non-existent element will report an error.
print(my_list.reverse()) #Direct printing result is None
print(my_list) #list is inverted at output

my_list.clear() #list cleared
print(my_list)
sort()
sort(reverse=True)

nums = [9.23, 9, 3, 6, 1, 0]
nums.sort() #Ranking from small to large
nums.sort(reverse=True) #Ranking from large to small
nums.extend(my_list) #Add elements to a list
print(nums)

new_list = nums + my_list + stu_name #merge
print(new_list)
print(new_list * 3) #Replicate several times

list practice

users = ['wrp','nhy','haha']
#Check whether the user name exists

for i in range(5):
    username = input("Please enter a user name:")
    # If the user does not exist, you can register.
    #if users.count(username) > 0:
    if username not in users: #In is the judgment of not being in.
        print("Users who are not registered can register")
        users.append(username)
    else:
        print("Users have been registered")
        
#The most primitive way to get list values is to get elements by calculating subscripts each time.
passwords = ['123456','123123','7891234','password']
count = 0
while count < len(passwords):
    s = passwords[count]
    print(s)
    count+=1
passwords = ['123456','123123','7891234','password']
#for loops directly loop through a list, and each looping takes its worth
for p in passwords:
    print(p)
#Modify the content in passwords
passwords = ['123456','123123','7891234','password']
index = 0
for p in passwords:
    passwords[index] = 'abc'+p
    index+=1
print(passwords)
#Use enumeration functions to calculate subscripts and elements
passwords = ['123456','123123','7891234','password']
for index,p in enumerate(passwords):
    passwords[index] = 'abc' + p
    print(index, p)
print(passwords)

Section
Slices are also suitable for Strings

l = ['a','b','c','d','e','f','g','h','i']
print(l[0:3]) #Look at your head and your tail
print(l[:5]) #If the colon is not written before the colon, it is taken from 0.
print(l[4:]) #If it is not written after the colon, it means the end.
print(l[:]) #Don't write colons before and after, take all of them.
print(l[0:8:2]) #Starting at 0, take one every two.


nums = list(range(1,101)) #range() generates a list
print(nums[1::2]) #Take even numbers less than 100
print(nums[::2]) #Take odd numbers less than 100
print(nums[::-2]) #Step size is positive, from left to right, step size is negative, from right to left

String slicing

#String slicing
words = 'The Mid-Autumn Festival has classes'
print(words[::-1])
for index,w in enumerate(words):
    print(index, w)

Palindrome algorithm

#Palindrome arithmetic, conversely, used to be the same, such as'Shanghai tap water comes from the sea', 12321
for i in range(10):
    str = input("Please enter a string:")
    
    if len(str) < 1:
            print("String length must be greater than or equal to")
    elif str == str[::-1]:
        print("It's palindrome.")
    else:
        print("Not palindrome.")

tuple

Tuples cannot be modified. If a tuple has only one element, you need to add commas after definition, otherwise brackets are considered operators.
Create tuples

tup1 = ()
tup2 = (1,2,3,4,5,6)
tup3 = ('google','baidu',1000,2000)
tup4 = (50,)#When there is only one element in a tuple, add a comma later

Access tuple

tup = ('google','baidu',1000,2000)
print(tup[1])

Modifying tuples

tup = ('google','baidu',1000,2000)
tup1 = ('abc','xyz')
tup3 = tup + tup1
print(tup3)

Delete tuple

tup = ('google','baidu',1000,2000)
del tup

Tuple operation

#Tuple operation
print(len((1,2,3)))
print((1,2,3)+(4,5,6))
print(3 in(1,2,3))

for x in(1,2,3):
    print(x)

tup =(1,2,3,4,5)
len(tup) #Finding tuple length
max(tup) #Find the maximum value in tuples
min(tup) #Finding the Minimum Value in Tuples

seq = [1,2,3,4,5]
tup = tuple(seq) #Replace lists with tuples

Dictionaries

xiaojun ={
    'name':'xioajun',
    'age': 21,
    'sex':'male',
    'addr':'Beijing',
    'phone':'13266568006'
}

increase

stus = {}
stus['name'] = 'Small army'
stus['name'] = 'Hailong'
stus.setdefault('name', 'Sails') #If the key already exists, setdefault does not modify the value of the key
stus.setdefault('age',  18)
stus.setdefault('sex', 'male')
stus.setdefault('addr', 'Beijing')
stus.setdefault('phone', '1961231231')
stus.update({'money':1000}) #Add a dictionary to stus

modify

stus['name'] = 'Xiaopeng'

query

print(stus['addr'])
print(stus.get('sex','male')) #If not, the second parameter in get() returns the default value
print(stus.keys()) #All key
print(stus.values()) #All value s

for k in stus:
    print(k, '===>',stus.get(k))

for k,v in stus.items():
    print(k, '====>', v)

delete

del stus['phone']
stus.pop('addr')
stus.popitem() #Random deletion
del stus #Delete the whole dictionary

Multilayer nesting of dictionary values

all_stus = {
    'xiaojun':{
        'name': 'xiaojun',
        'age': 21,
        'sex': 'male',
        'addr': 'Beijing',
        'phone': '13266568006',
        'id': 1,
        'cars':['Wrangler','911','Wild horse','Rolls-Royce'],
    },
    'hailong':{
        'name': 'hailong',
        'age': 21,
        'sex': 'male',
        'addr': 'Beijing',
        'phone': '13266569006',
        'id': 2,
        'bags':{
            'qianbao':['lv', 'ysl'],
            'beibao':['coach','abc']
        }
    }
}

all_stus['xiaojun']['cars'].append('Wuling Hongguang') #Add values to xiaojun's car
print(len(all_stus['xiaojun']['cars'])) #Statistics of the number of car s in xiaojun
all_stus['hailong']['sex'] = 'female'  #Change hailong's sex to female
all_stus['hailong']['bags']['qianbao'].remove('lv') #Delete lv from qianbao in bags
all_stus['hailong']['bags']['kuabao']=['bac'] #Add a kuabao
all_stus['hailong']['bags']['kuabao'].append('lv2') #Adding lv2 in kuabao
all_stus['hailong']['bags'].pop('kuabao') #Delete kuabao

Common String Methods

password = ' 123456 \n 456789 '
print(password.strip())  #By default, space and newline characters on both sides of the string are removed
print(password.rstrip()) #The space on the right
print(password.lstrip()) #The space on the left

password1 = 'jpg 1233456789 .jpg'
print(password1.strip('.jpg')) #Remove both sides of the string. jpg

print(password1.upper()) #Turn capitalization
print(password1.lower()) #Turn to lowercase
print(password1.capitalize()) #Change the initial letter to uppercase
print(password1.count('jpg')) #Number of occurrences of strings
print(password.replace('Tan Ai Ling','Go up the hill and fight against tigers')) #Replace strings when found, fail to find and report errors

filename = 'a.mp3'
print(filename.endswith('.mp3')) #Determine whether to end with xxx
print(filename.startswith('196')) #Judgment begins with xxx
#'{name},{age}'.format(name='hhh',age=18)

names = 'Xiaojun, Hailong, Yang Fan, Dapeng'
names1 = 'Xiaojun Hailong Yang Fan     Dapeng'
print(names.split(',')) #Separating strings into list s with delimiters
print(names1.split()) #Cut by default when not specified

Posted by dewbie on Sun, 21 Apr 2019 14:54:35 -0700