3 Python data structures and 13 creation methods. This summary is awesome!

There are several data structures commonly used in Python. But the three that we use most are strings, lists, and dictionaries.
Insert picture description here
In fact, the most basic thing to learn any programming language is to learn its data structure.

In Python, the concept of data structure is also super important. Different data structures have different functions for us to call.

Next, we will introduce the creation methods of strings, lists, and dictionaries respectively.

3 ways to create strings

① Single quote (''), create a string

a = 'I am a student'
print(a)

The results are as follows:
Insert picture description here

② Double quotes (" "), create a string

b = "I am a teacher"
print(b)

The results are as follows:
Insert picture description here

③ Continue 3 single quotes or 3 single quotes to create a multi-line string

c = '''
I am a student
My name is黄伟
I am a teacher
My name is陈丽
'''
print(c)

The results are as follows:
Insert picture description here

5 ways to create lists

① Use [] to create a list

a = [1,2,3]
print(a)

The results are as follows:
Insert picture description here

② Create a list with list

b = list('abc')
print(b)

c = list((1,2,3))
print(c)

d = list({
    
    "aa":1,"bb":3}) #对于字典,生成的是key列表。
print(d)

The results are as follows:
Insert picture description here

③ Use range to create a list of integers

e = list(range(10))
print(e)

The results are as follows:
Insert picture description here

④ Create a list with list comprehension

f = [i for i in range(5)]
print(f)

The results are as follows:
Insert picture description here

⑤ Use list and [] to create an empty list

g = list()
print(g)

h = []
print(h)

The results are as follows:
Insert picture description here

5 ways to create a dictionary

① Use {} to create a dictionary

a = {
    
    'name':'陈丽','age':18,'job':'teacher'}
print(a)

b = {
    
    'name':'陈丽','age':18,'job':['teacher','wife']}
print(b)

The results are as follows:
Insert picture description here

② Create a dictionary with dict

c = dict(name='张伟',age=19)
print(c)

d = dict([('name','李丽'),('age',18)])
print(d)

The results are as follows:
Insert picture description here

③ Create a dictionary with the zip function

x = ['name','age','job']
y = ['陈丽','18','teacher']
e = dict(zip(x,y))
print(e)

The results are as follows:
Insert picture description here

④ Create an empty dictionary with {},dict

f = {
    
    }
print(f)

g = dict()
print(g)

The results are as follows:
Insert picture description here

⑤ Use fromkeys to create a dictionary whose value is empty

h =dict.fromkeys(['name','age','job'])
print(h)

The results are as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_41261833/article/details/109278148