Basic data type --- list

Definition and creation of lists

Definition: [] is separated by commas, according to the index, various data types are stored, each position represents an element

1
list_test = ['Zhang San','Li Si']#The first type
2
list_test = list('zhangshan')#The second type
3
list_test = list(['Zhang San','Li Si'])#The first Features and common operations of the three
lists

characteristic:

1. Can store multiple values

2. Define the list elements in the order from left to right, and the subscripts are accessed sequentially from 0, in order


3. The value corresponding to the specified index position can be modified, variable
Common operations:

#索引
>>> l = ['egon','alex','seven','yuan']
>>> l[0]
'egon'
>>> l[2]
'seven'
#切片
>>> l = ['egon','alex','seven','yuan']
>>> l[0:2]#取0到2
['egon', 'alex']
>>> l[2:5]#取从开头始到五
['seven', 'yuan']
>>> l[:2]#与0:2相同
['egon', 'alex']
>>> l[2:]#从2开始到最后
['seven', 'yuan']
>>> l[:]#取所有
['egon', 'alex', 'seven', 'yuan']
>>> l[::2]#步长,隔两取一个
['egon', 'seven']
>>> l[::-1]
['yuan', 'seven', 'alex', 'egon']

#追加
>>> l.append("eva")
>>> l
['egon', 'alex', 'seven', 'yuan', 'eva']

#删除
>>> l.remove('eva')
>>> l
['egon', 'alex', 'seven', 'yuan']
>>> l.pop()
'yuan'
>>> l
['egon', 'alex', 'seven']

#长度
>>> len(l)
3

#包含
>>> 'seven' in l
True
>>> 'yuan' in l
False

#循环:为什么是“i”?
>>> for i in l:
    print(i)


egon
alex
seven

Lists and Strings - split and join

#分割
>>> s = 'hello world'
>>> s.split(' ')
['hello', 'world']
>>> s2= 'hello,world'
>>> s2.split(',')

#连接
>>> l = ['hi','eva']
>>> '!'.join(l)
'hi!eva'




Guess you like

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