shivency

1、列表的索引很有玩头,包括负索引、切片(slice)

  但试图对空列表索引会引发错误;

 

2、使用List.split(),会自动生成字符列表

1 metals= \'1 2\'.split()
2 
3 print metals                        #[\'1\', \'2\']
4 
5 print metals[0] + metals[1]         #12


3、这里说明一点,调用list方法,返回通常是None,而不想想当然的修改后的列表(除了pop之外)

 1 numbers= \'1 2 3 4 5 6 7\'.split()        #[\'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\']
 2 print numbers
 3 
 4 numbers.sort()                          #[\'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\']
 5 print numbers
 6 
 7 numbers.reverse()                       #[\'7\', \'6\', \'5\', \'4\', \'3\', \'2\', \'1\']
 8 print numbers
 9 
10 print numbers.sort()                    #None
11 print numbers.reverse()                 #None

 

4、列表与字符串

列表有可变性,而字符串在创建之后不能修改;元组在创建之后同样不能修改

所以列表的别名可能导致bug,字符串则是安全的。

1 a= \'abcde\'
2 a[0]= \'d\'
3 print a
4 
5 #Traceback (most recent call last):
6 #  File "C:\Users\dsdn\workspace_python\excel_excise\src\excel_op.py", #line 3, in <module>
7 #    a[0]= \'d\'
8 #TypeError: \'str\' object does not support item assignment

 

5、文件

  挺重要的

 

练习:

1、利用切片功能,创建两个新的列表cool_temp和warm_temp,分别包含temp中低于和高于20°的温度值

 1 temp=[]
 2 a= 15
 3 
 4 for i in range(10):
 5     temp.append(a)
 6     a= a+1
 7     
 8 print temp                      #[15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
 9 temp.sort(cmp=None, key=None, reverse=False)    #保证temp是正序排列
10 
11 for index in range(10):         #不能直接用10
12     if temp[index]> 20:
13         break
14  
15 cool_temps= temp[:index]
16 warm_temps= temp[index:]
17 
18 print cool_temps                #[15, 16, 17, 18, 19, 20]
19 print warm_temps                #[21, 22, 23, 24]

 

2、画一个能够说明下面代码效果的内存图

1 values= [0,1,2]
2 values[1]= values
3 
4 print values                #[0, [...], 2]
5 print values[1]             #[0, [...], 2]

不知是否正确

 

3、字符串是不可变的,为什么说可变的字符串可能是有用的?你认为python要把字符串变成不可变的原因是什么?

不知道怎么回答,暂记

分类:

技术点:

相关文章:

  • 2021-11-23
  • 2021-11-23
  • 2021-08-05
  • 2022-03-10
  • 2021-05-25
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
猜你喜欢
  • 2022-12-23
  • 2021-09-20
  • 2022-12-23
  • 2021-08-21
  • 2021-12-31
  • 2021-07-22
  • 2022-03-05
相关资源
相似解决方案