【Python】2020.02.24学习笔记01|列表、切片

小题目:写一个函数:统计一句话的单词个数,找到长度最长的单词,函数计算结果返回2个值。一个是单词个数,一个是最长的字母个数.

【标准答案】

image.png
def count_word_info(s):
    ##先判断s是否是字符串
    if not isinstance(s,str):
        return None
    new_sentence=""
    ##把标点符号给过滤掉
    for i in s:
        if i ==" " or (i>='a' and i<='z') or (i>='A' and i<='Z'):
            new_sentence+=i
        else:
            new_sentence+=" "##如果标点和单词连在一起,把标点替换成空格

    word_num=len(new_sentence.split())
    word_max_length=0
    for i in new_sentence.split():
        ##找到最大的单词
        if len(i)>word_max_length:
            word_max_length=len(i)
    return word_num,word_max_length

print(count_word_info("Hello , everyone!Today is Monday . "))

列表、元素、字典

列表

image.png

例子

>>> a=[]
>>> type(a)


>>> a=[1,1.2,3e3,"abc",(1,2,3),[12,3],{1:2},set([1,2,3])]
>>> a
[1, 1.2, 3000.0, 'abc', (1, 2, 3), [12, 3], {1: 2}, {1, 2, 3}]
>>> type(a)

>>> a[0]
1
>>> a[1]
1.2
>>> a[2]
3000.0
>>> a[4]
(1, 2, 3)
>>> a[-1]
{1, 2, 3}
>>>

判断一个变量是否为列表类型

>>> isinstance(a,list)
True
>>>

切片

起始位置、结束位置、步长

>>> a[::]
[1, 1.2, 3000.0, 'abc', (1, 2, 3), [12, 3], {1: 2}, {1, 2, 3}]
>>> a[:]
[1, 1.2, 3000.0, 'abc', (1, 2, 3), [12, 3], {1: 2}, {1, 2, 3}]
>>> a[:4]
[1, 1.2, 3000.0, 'abc']
>>> a[-4::-1]
[(1, 2, 3), 'abc', 3000.0, 1.2, 1]
>>> a[::2]
[1, 3000.0, (1, 2, 3), {1: 2}]
>>> a[-4::-2]
[(1, 2, 3), 3000.0, 1]
>>> a[-4::2]
[(1, 2, 3), {1: 2}]
>>>

如果切片的长度过长,系统不会报错,有多少就会显示多少,但是如果找的元素不在,就会报错

>>> a[:100]
[1, 1.2, 3000.0, 'abc', (1, 2, 3), [12, 3], {1: 2}, {1, 2, 3}]
>>> a[100]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: list index out of range
>>>

创建列表

image.png

访问列表

image.png

更新列表

image.png

插入数据

>>> b=[]
>>> b.append(1)
>>> b.append("a")
>>> b.insert(0,122)
>>> b
[122, 1, 'a']
>>>

列表可以相乘可以相加

>>> [1]*10
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> [2.3]+[b,c]
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'c' is not defined
>>> [1,2,3]+[9,7,6]
[1, 2, 3, 9, 7, 6]
>>>
>>> [10.1]*100000000
10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 10.1, 

删除数据

>>> a=list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[0]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> del a[1:5]
>>> a
[1, 6, 7, 8, 9]
>>>

如果这个值不在列表中,删除会报错,可以采取判断的方式

>>> a
[1, 6, 7, 8, 9]
>>> a.remove(1)
>>> a
[6, 7, 8, 9]
>>> a.remove(1)
  File "", line 1
    a.remove(1)
              ^
SyntaxError: invalid character in identifier
>>> if 6 in a:
...     a.remove(6)
...
>>> a
[7, 8, 9]
>>>

你可能感兴趣的:(【Python】2020.02.24学习笔记01|列表、切片)