Python--009 sequence

sequence

Lists, tuples, strings

Common ground:

1. You can get each element by index
2. The default index starts from 0
3. You can get a set of elements within a certain range in the form of slices
4. Many common operators, *, +, in/not in

Data with the above characteristics is a sequence (list, tuple, string)

· Built-in functions for sequences (BIFs)

1. List list()/list(iterator)

Convert an iterable object to a list

a='Hello'
print (list(a))#['H', 'e', 'l', 'l', 'o']

2. tuple()/tuple(iterator)
converts an iterable object into a tuple

  a='Hello'
  print (tuple(a))#('H', 'e', 'l', 'l', 'o')

3, str (object): object is converted to a string

print str(10)#字符串10

4. len(...): Returns the length of a parameter

    a='Hello'
    print len(a) #5

5. max(): Returns the maximum value in the sequence or parameter set

    l=[1,2,3,4,5]
    print max(l)  #5

6. min(): Returns the minimum value of a sequence or set

    l=[1,2,3,4,5]
  print min(l)  #1
   l=['a','b','c']
   print max(l)#c ASCII 对应数值大

l=[1,2,3]
l.append('a') 
print l  #[1, 2, 3, 'a']
print min(l) #1
print max(l) #a的编码表为97  返回a

  这个比较在python2 可以,如果python3不同类型比较报错

7. sum(iterator[,start=0]): Returns the sum of iterable objects and optional parameters

a=[1,2,3]
print sum(a) #6
print sum(a,10) #16

8. sorted(): sort() is similar to: sorting

a=[3,1,2]
print sorted(l) #[1,2,3]

9. reversed(): reverse() iterates objects in reverse order

a=[4,5,3,8,1]
print reversed
list(reversed(sorted(a)))
print a  #[8,5,4,3,1]
#如果直接reversed(sorted(a))不行 这是可迭代对象 必须加list

10. enumerate(): Returns the tuple sequence (subscript, element) iterable object

l=['a','b','c']
print list(enumerate(l))
#[(0, 'a'), (1, 'b'), (2, 'c')]

11. zip(): Return the packaged tuple

a=[1,2,3,4,5,6,7,8]
b=[4,5,6,7,8]
print list(zip(a,b))
#[(1, 4), (2, 5), (3, 6), (4, 7), (5, 8)]

a=[1,2,3,4,5,6,7,8]
b=['a','b','c','d']
print list(zip(a,b))#[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

Supplementary concept:
Sequence: has 4 features
Iteration: Activities that repeat the feedback process, such as for loops, the repeated process is
iterable objects: multiple elements are taken out and used, the iterable object contains the sequence

可迭代对象>序列>元祖,字符串,列表

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324549327&siteId=291194637