The following focuses on lists, tuples and strings.
list1=['hello','world']
print list1
list2=[1,2,3]
print list2
Output:
[' hello', 'world']
[1, 2, 3]
As you can see, the creation method here is very similar to the array in javascript.
It is very effective to create a list of strings through the list function (in fact, list is a type rather than a function):
list3=list("hello")
print list3
Output:
[' h', 'e', 'l', 'l', 'o']
t1=1,2,3
t2="jeffreyzhao","cnblogs"
t3=(1,2,3,4)
t4=()
t5=(1,)
print t1,t2,t3,t4,t5
Output:
(1, 2, 3) (' jeffreyzhao', 'cnblogs') (1, 2, 3, 4) () (1,)
From the above analysis, we can get:
a. Comma separated some values, the tuple is automatically created;
b. Tuples are enclosed by parentheses most of the time;
c. Empty tuples can be represented by parentheses without any content;
d. Tuples containing only one value must add a comma (,);
The tuple function is almost the same as the list function of a sequence: it takes a sequence (note the sequence) as a parameter and converts it to a tuple.
If the parameter is a tuple, then the parameter will be returned as is:
t1=tuple([1,2,3])
t2=tuple("jeff")
t3=tuple((1,2,3))
print t1
print t2
print t3
t4=tuple(123)
print t4
Output:
(1, 2, 3)
(' j', 'e', 'f', 'f')
(1, 2, 3)
Traceback (most recent call last):
File "F:\Python\test.py", line 7, in
t4=tuple(123)
TypeError: 'int' object is not iterable
str1='Hello world'
print str1
print str1[0]for c in str1:
print c
Output:
Hello world
H
H
e
l
l
o
w
o
r
l
d
str1='Hello,%s'%'world.'
print str1
strs=('Hello','world') #Tuple
str1='%s,%s'% strs
print str1
d={'h':'Hello','w':'World'} #dictionary
str1='%(h)s,%(w)s'% d
print str1
Output:
Hello,world
Hello,World
str1='%s,%s'%'Hello','world'
print str1
Output:
Traceback (most recent call last):
File "F:\Python\test.py", line 2, in
str1='%s,%s'%'Hello','world'
TypeError: not enough arguments for format string
str1='%s%%'%100
print str1
Output: 100%
from math import pi
str1='%.2f'% pi #Accuracy 2
print str1
str1='%10f'% pi #Field width 10
print str1
str1='%10.2f'% pi #Field width 10, precision 2
print str1
Output:
3.14
3.141593
3.14
String formatting also contains many other rich conversion types, please refer to official documents.
It works similarly to variable substitution in many UNIX Shells, as shown below:
from string import Template
str1=Template('$x,$y!')
str1=str1.substitute(x='Hello',y='world')
print str1
Output:
Hello,world!
from string import Template
str1=Template('Hello,w${x}d!')
str1=str1.substitute(x='orl')
print str1
Output:
Hello,world!
from string import Template
str1=Template('$x$$')
str1=str1.substitute(x='100')
print str1
Output: 100$
from string import Template
d={'h':'Hello','w':'world'}
str1=Template('$h,$w!')
str1=str1.substitute(d)
print str1
Output:
Hello,world!
In addition to formatting, Python strings also have many built-in practical methods. You can refer to the official documentation, which will not be listed here.
From lists, tuples, and strings, you can "abstract" some common common methods of sequences (not CRUD as you think),
These operations include: indexing, slicing, adding, multiplying, and checking whether an element is a member of the sequence.
In addition, there are built-in functions for calculating sequence length, maximum and minimum elements, etc.
str1='Hello'
nums=[1,2,3,4]
t1=(123,234,345)
print str1[0]
print nums[1]
print t1[2]
Output
H
2
345
The magic is that the index can start from the last position (from right to left), and the number is -1:
str1='Hello'
nums=[1,2,3,4]
t1=(123,234,345)
print str1[-1]
print nums[-2]
print t1[-3]
Output:
o
3
123
Fragmentation operations are used to access elements within a certain range. Fragmentation is achieved by two indexes separated by colons:
nums=range(10)
print nums
print nums[1:5]
print nums[6:10]
print nums[1:]
print nums[-3:-1]
print nums[-3:] #Include the element at the end of the sequence, blank the last index
print nums[:] #Copy the entire sequence
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4]
[6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[7, 8]
[7, 8, 9]
nums=range(10)
print nums
print nums[0:10] #The default step size is 1 equivalent to nums[1:5:1]
print nums[0:10:2] #Step size is 2
print nums[0:10:3] #Step size is 3
## print nums[0:10:0] #Step size is 0
print nums[0:10:-2] #The step size is-2
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
[0, 3, 6, 9]
[]
str1='Hello'
str2=' world'
print str1+str2
num1=[1,2,3]
num2=[2,3,4]
print num1+num2
print str1+num1
Output:
Hello world
[1, 2, 3, 2, 3, 4]
Traceback (most recent call last):
File "F:\Python\test.py", line 7, in
print str1+num1
TypeError: cannot concatenate 'str' and 'list' objects
print [None]*10
str1='Hello'
print str1*2
num1=[1,2]
print num1*2
print str1*num1
Output:
[ None, None, None, None, None, None, None, None, None, None]
HelloHello
[1, 2, 1, 2]
Traceback (most recent call last):
File "F:\Python\test.py", line 5, in
print str1*num1
TypeError: can't multiply sequence by non-int of type 'list'
str1='Hello'
print 'h'in str1
print 'H'in str1
num1=[1,2]
print 1in num1
Output:
False
True
True
str1='Hello'
print len(str1)
print max(str1)
print min(str1)
num1=[1,2,1,4,123]
print len(num1)
print max(num1)
print min(num1)
Output:
5
o
H
5
123
1
Simply put, a dictionary is a collection of key-value pairs wrapped in braces. (Key-value pairs are also called items)
adict ={}
adict ={key1:value2, key2:value2, …}
Or use the dict() function, for example, adict = dict() or adict = dict((['x',1],['y',2])) Is it correct?
adict = dict(['x',1],['y',2]). Create a dictionary with keyword parameters, such as: adict= dict(name='allen',age='40')
Or use the fromkeys() method, for example, adict = {}.fromkeys(('x','y'), -1) The value of the dictionary created in this way is the same. If you don't give a value, the default is None.
The key and value are separated by a colon ":";
Item and item are separated by comma ",";
The keys in the dictionary must be unique, and the values need not be unique.
The form adict[key] returns the value corresponding to the key key. If the key is not in the dictionary, a KeyError will be raised.
How to check if the key is in the dictionary? The has_key() method has the form: adict.haskey('name') with –>True, without –>False
in and not in have the form:'name' in adict with –>True, without –>False
How to update the dictionary?
adict[new_key] = value form to add an item
adict[old_key] = new_value
del adict[key] delete the key item / del adict delete the entire dictionary
adict.pop(key) delete the key item and return the value corresponding to the key
a. The dictionary does not support splicing and repetition operators (+, *)
b. Dictionary comparison operation
First compare the length of the dictionary, which is the number of elements in the dictionary
Key comparison
Value comparison
example:
adict ={}
bdict ={'name':'allen','age':'40′}cmp(adict, bdict) #Less than –>-1 is greater than –>1 is equal to –>0
len() returns the length of the dictionary
hash() returns the hash value of the object, which can be used to determine whether an object can be used as a dictionary key
dict() factory function, used to create a dictionary
adict.keys() returns a list containing all the keys of the dictionary;
adict.values() returns a list containing all values of the dictionary;
adict.items() returns a list containing all (key, value) primitives;
adict.clear() delete all items or elements in the dictionary;
adict.copy() returns a copy of a shallow copy of the dictionary;
adict.fromkeys(seq, val=None) creates and returns a new dictionary, using the elements in seq as the keys of the dictionary, and val as the initial value corresponding to all keys in the dictionary (the default is None);
adict.get(key, default = None) returns the value corresponding to the key in the dictionary. If the key does not exist in the dictionary, it returns the value of default (default is None by default);
adict.has_key(key) If the key is in the dictionary, return True, otherwise return False. Now use in and not in;
adict.iteritems(), adict.iterkeys(), adict.itervalues() are the same as their corresponding non-iterative methods, the difference is that they return an iterator instead of a list;
adict.pop(key[,default]) is similar to the get method. If the key exists in the dictionary, delete and return the vuale corresponding to the key; if the key does not exist and the default value is not given, a keyerror exception will be raised;
adict.setdefault(key, default=None) is similar to the set() method, but if there is no Key key in the dictionary, adict[key] = default is assigned to it;
adict.update(bdict) Add the key-value pairs of the dictionary bdict to the dictionary adict.
1、 Traverse the key of the dictionary
for key in adict.keys():print key
2、 Traverse the value of the dictionary
for value in adict.values(): print value
3、 Traverse the items (elements) of the dictionary
for item in adict.items():print item
4、 Traverse the key-value of the dictionary
for item,value in adict.items(): print 'key=%s, value=%s'%(item, value)for item,value in adict.iteritems(): print ‘'key=%s, value=%s'%(item, value)
Note: for item,value in adict.items(): print'key=%s','value=%s', %(item, value) this way of writing is wrong
1、 One key cannot be allowed to correspond to multiple values;
2、 The key must be hashable.
Sets were introduced in Python 2.3 and can usually be created directly using a newer version of Python, as shown below:
strs=set(['jeff','wong','cnblogs'])
nums=set(range(10))
The collection is mainly used to check membership, so the copy is ignored. As shown in the following example, the output collection content is the same.
set1=set([0,1,2,3,0,1,2,3,4,5])
print set1
set2=set([0,1,2,3,4,5])
print set2
The output is as follows:
set([0, 1, 2, 3, 4, 5])
set([0, 1, 2, 3, 4, 5])
This is very similar to a dictionary. It can be simply understood that the set is a dictionary without a value.
strs=set(['jeff','wong','cnblogs'])
print strs
The output is as follows:
set(['wong', 'cnblogs', 'jeff'])
a. Intersection union
set1=set([1,2,3])
set2=set([2,3,4])
set3=set1.union(set2)
print set1
print set2
print set3
Output:
set([1, 2, 3])
set([2, 3, 4])
set([1, 2, 3, 4])
The union operation returns the union of the two sets without changing the original set. Use the bitwise AND (OR) operator "|" to get the same result:
set1=set([1,2,3])
set2=set([2,3,4])
set3=set1|set2
print set1
print set2
print set3
The output is exactly the same as the above union operation.
set1=set([1,2,3])
set2=set([2,3,4])
set3=set1&set2
print set1
print set2
print set3
print set3.issubset(set1)
set4=set1.copy()
print set4
print set4 is set1
The output is as follows:
set([1, 2, 3])
set([2, 3, 4])
set([2, 3])
True
set([1, 2, 3])
False
set1=set([1])
print set1
set1.add(2)
print set1
set1.remove(2)
print set1
print set1
print 29in set1
set1.remove(29) #Remove non-existent item
Output:
set([1])
set([1, 2])
set([1])
set([1])
False
Traceback (most recent call last):
File "F:\Python\test.py", line 9, in
set1.remove(29) #Remove non-existent item
KeyError: 29
Sets are mutable, so they cannot be used as dictionary keys. The collection itself can only contain immutable values, so it cannot contain other collections:
set1=set([1])
set2=set([2])
set1.add(set2)
The output is as follows:
Traceback (most recent call last):
File "F:\Python\test.py", line 3, in
set1.add(set2)
TypeError: unhashable type: 'set'
set1=set([1])
set2=set([2])
set1.add(frozenset(set2))
print set1
Output:
set([1, frozenset([2])])
Recommended Posts