In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
An example analysis of basic data types and their common usage in Python. In order to solve this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
List
First of all, List is included by []. Each element is separated by (comma). Any data type can be nested in List, and data types can be nested with each other (except set), such as:
# define a list
Li = ['name':, 1, True, (' baked, 'caged,), [1,2,3], {' salted fish'}, {1,2}]
# ergodic
For i in li:
# print data types and values
Print (type (I), I)
The value of the list
# define a list
Li = ['name':, 1, True, (' baked, 'caged,), [1,2,3], {' salted fish'}, {1,2}]
# take the value through the index. Note that the index starts from 0.
Temp1 = li [0]
Print (temp1) # a
# list values are nested in the list
Temp2 = li [4] [0]
Print (temp2) # 1
# remember string slicing? List can do the same, but the value is still a list.
Temp3 = li [1:5:]
Print (temp3) # [1, True, ('baked,' c'), [1, 2, 3]]
List modification
# remember mutable types and immutable types? Variable means that the value of an element can be changed.
Li = ['await,' baked,'c']
Li [0] ='b'
Print (li)
# change the value of part of the index with slicing
Li [0:2] = ['clockjobo']
Print (li)
# error demonstration: immutable data types cannot change the value of an index
Str1 = 'abc'
Print (str1 [0]) # can print the value of an index
Str1 [0] ='1' # changing the value of an index throws an exception TypeError: 'str' object does not support item assignment
List deletion
Li = ['await,' baked,'c']
# Delete an element according to the index
Del li [0]
Print (li)
# Delete the element of an index and return the deleted value. Delete the last element by default
Li = ['await,' baked,'c']
Temp1 = li.pop () # assign the returned deleted value to a variable and print it.
Print (li)
Print (temp1)
Temp2 = li.pop (0) # you can also pass in the index to be deleted
Print (li)
Print (temp2)
# Delete the value by value and delete one from the leftmost
Li = [11,'22, 22, 33, 44, 22]
Li.remove (22)
Print (li)
Li = ['await,' baked,'c']
# clear the entire list
Li.clear ()
Print (li)
List insertion
# add a value to the specified index location
Li = [1,2,3,4,5,6]
Li.insert (2, 'lll') # insert (index location, value to add)
Print (li)
# append to the object
Li = [1,2,3,4,5,6]
Li.append ("aaa") # appends a single element
Li.append ([11,22,33]) # appended list as an element
Print (li)
# expand the list
Li = [1,2,3,4,5,6]
Li.extend ("aaa") # adds each element of the string to the original list
Li.extend ([11,22,33]) # add each element of the list to the original list
Print (li)
# merge two lists
Li1 = [1, 2, 3, 4]
Li2 = ['averse,' baked, 'crested,' d']
Li3 = li1+li2
Print (li3)
List query
# determine whether a value exists in the list and return a Bool value
Li = [1, 2, 3, 4]
Res = 2 in li
Print (res)
# determine how many times a value exists in the list
Li = [1,2,2,3,2,4]
Res = li.count (2)
Print (res)
# determine that a value is in the index of the list. There are multiple indexes that return the first value
Li = [1, 2, 3, 4]
Res = li.index (2)
Print (res)
# if there is no exception thrown
# li = [1, 2, 3, 4]
# res = li.index (6)
# print (res) # ValueError: 6 is not in list
List reversal
Li = [1,'a', 2,'b']
Li.reverse ()
Print (li)
List sort, maximum (minimum) valu
# Note that only data of the same type can be sorted. Take the maximum and minimum values, and you cannot mix numbers with strings.
Li = [8,2,6,8,5]
Li.sort () # sort
Print (li) li = ['baked,' 5percent, 'zonal,' yearly, 'ringing,' l']
Li.sort ()
Print (li)
# maximum
Print (max (li))
# minimum
Print (min (li))
Conversion between list and string
# convert string to list
Str1 = 'abcdefg'
Li = list (str1)
Print (li)
# convert a list to a string. Note that the list can only be full of strings
Li = ['1miles,' asides, 'canals,' 2']
S1 ='. Join (li)
Print (S1)
# the list contains numeric type
Li = [1,2, 'asides,' b']
# define an empty string first
S1 =''
# iterate through the list
For i in li:
# convert a numeric type to a string concatenated to an empty string defined earlier
S1 + = str (I)
Print (S1)
Tuple
Tuples are immutable, values cannot be changed according to the index, cannot be added and deleted, and tuples are included with (), such as:
Tu = (111,22,33,), [(1,2,3)], 222,333, True,)
Tuples can also be indexed, sliced, and traversed. It will not be demonstrated here.
There are two ways:
Count (a) # gets the number of specified elements that appear in the tuple
Index (a _) # gets the index of the specified element in the tuple
A little knowledge:
Tuples are also parentheses, and the method looks the same. In order to make it easier to distinguish and more intuitive, we usually add an extra comma after it, which is a good specification. For example:
Tu = (1, 2, 3,)
Dictionaries
The dictionary uses {} to include key-value pairs composed of key and value. The dictionary is an unordered collection list, and the dictionary cannot be used as a key value. The key value can only be unique. Other data types can still be nested in the dictionary, such as:
Dic = {
'K1':'v1'
'K2girls: 'v2'
'k3':'v3'
'K2percent: 'v4'
False: "aa"
0: "bb"
'k4legs: [1, 2, 3, 4]
'k5legs: {
'K1':'v1'
}
}
Print (dic)
Take a value
Dic = {
'K1':'v1'
'K2girls: 'v2'
'k3':'v3'
'K2percent: 'v4'
False: "aa"
0: "bb"
'k4legs: [1, 2, 3, 4]
'k5legs: {
'K1': 'v11'
}
}
# the dictionary is valued through key, and the list in the dictionary is still valued through the index
Print (dic ['K5'] [' K1']) # v11
Print (dic ['k4'] [0]) # 1
Print (dic ['kkkk']) # key that does not exist throws an exception KeyError
# it is recommended to use get,key to return value for existence, but not to return the second parameter.
Print (dic.get ('kkkk')) # returns None without throwing an exception (default)
Print (dic.get ('kkkk',' does not exist')) # returns' does not exist'at this time
Ergodic
Dic = {
'K1':'v1'
'K2girls: 'v2'
'k3':'v3'
'K2percent: 'v4'
False: "aa"
0: "bb"
'k4legs: [1, 2, 3, 4]
'k5legs: {
'K1': 'v11'
}
}
# in the dictionary, key is the same as the last overlay, and the front True is 1 False is 0. It can be observed that only false,value in the key is overwritten 'bb'' later.
# the default cycle is the key value
Print ('one:')
For i in dic:
Print (I)
# the default cycle is the key value
Print ('two:')
For i in dic.keys ():
Print (I)
# the loop is the value value
Print ('three:')
For i in dic.values ():
Print (I)
# Loop key and value
Print ('four:')
For iMagazine j in dic.items ():
Print (iMagnej)
Fromkeys
# use the first parameter as the key value and the second parameter as the unified value to generate a dictionary
Dic0 = dict.fromkeys ('a') # the second parameter does not write value defaults to None, null value, which is not equal to empty string ('')
Print (dic0)
Dic1 = dict.fromkeys ('averse,' b')
Print (dic1)
Dic2 = dict.fromkeys ('asides, [1, 2, 3]) # the second parameter generates a dictionary as a unified value
Print (dic2)
Dic3 = dict.fromkeys (['axiaqingjiaomiao baozhongjingc'], [1min2prr3])
Print (dic3)
Add
Dic = {
'K1':'v1'
'K2girls: 'v2'
'k3':'v3'
}
# key that already exists will modify the value of the corresponding key, and key that does not have will add the corresponding value
Dic ['k4'] =' v4'
Print (dic)
# key that already exists returns the corresponding value. If not, add key and value.
V1 = dic.setdefault ('K1N1,' v111')
Print (dic, v1)
V2 = dic.setdefault ('k123regions,' v123')
Print (dic, v2)
Modify
Dic = {
'K1':'v1'
'K2girls: 'v2'
'k3':'v3'
'k4century: 'v4'
'k5times: 'v5'
}
# overwrite the previous value by using the unique feature of key
Dic ['K1'] =' v111'
Print (dic)
# update (input data in dictionary form)
Dic.update ({'K2Qing:' v222'})
Print (dic)
# Update multiple
Dic.update ({'k3pm:' v33319', 'v333')
Print (dic)
# you can also write key=value directly
Dic.update (k5cm / k555')
Print (dic)
# updating a key that does not exist is equivalent to adding
Dic.update (k6pm / k666')
Print (dic)
Delete
# delete and get the value pop (parameter 1, parameter 2)
Res = dic.pop ('K1')
Print (dic,res)
# throw an exception if you delete a key that does not exist without passing in the second parameter
# res = dic.pop ('k111')
# print (dic,res) # KeyError
Res = dic.pop ('k111fujinghee key does not exist')
Print (dic,res) # returns the second parameter
# Delete the last pair of keys and values in the dictionary and return them
KBI v = dic.popitem ()
Print (dic,k,v)
# clear the dictionary
Dic.clear ()
Print (dic) on the basic data types in Python and their commonly used sample analysis questions are shared here, I hope the above content can be of some help to you, if you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.