python list 基本操作

1. 整形和字符串的转换

>>> a = 2

>>> print str(2)
2
>>> b = '1244'
>>> print int(b)
1244
>>> print int(b) + 1

1245


2. 怎样定义list 类型变量

>>> list[]
  File "<stdin>", line 1
    list[]
         ^
SyntaxError: invalid syntax
>>> list
<type 'list'>

>>> list=[]



3. 怎样向list中添加元素

>>> list.append('12', '3')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: append() takes exactly one argument (2 give
>>> list.append(('12', '3'))

>>> list.append(('12', '3'))


4. 怎样计算list的大小,有几个元素

>>> print len(list)

2


5.怎样遍历list中的元素

>>> for element in list
  File "<stdin>", line 1
    for element in list
                      ^
SyntaxError: invalid syntax
>>> for element in list print(element)
  File "<stdin>", line 1
    for element in list print(element)
                            ^
SyntaxError: invalid syntax
>>> for element in list
  File "<stdin>", line 1
    for element in list
                      ^
SyntaxError: invalid syntax
>>> for element in list \n print element
  File "<stdin>", line 1
    for element in list \n print element
                                       ^
SyntaxError: unexpected character after line continuation character
>>> 
>>> for element in list 
  File "<stdin>", line 1
    for element in list 
                       ^
SyntaxError: invalid syntax
>>> for element in list: print element
... 
('12', '3')
('12', '3')
>>> print len(list)

2


6.怎样使用list的元素?

>>> print list[0,0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
>>> print list[0:0]
[]
>>> print list[1:0]
[]
>>> print list[1:1]
[]
>>> print list[2:1]
[]
>>> print list[0]
('12', '3')
>>> print list[1]
('12', '3')
>>> print list[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> print list[0][0]

12


7.怎样判断变量的类型type 用法

>>> type list[0][0]
  File "<stdin>", line 1
    type list[0][0]
            ^
SyntaxError: invalid syntax
>>> type (list[0][0])
<type 'str'>
>>> type list
  File "<stdin>", line 1
    type list
            ^
SyntaxError: invalid syntax
>>> type int
  File "<stdin>", line 1
    type int
           ^
SyntaxError: invalid syntax
>>> type(list[0][0])
<type 'str'>
>>> type(int(list[0][0]))
<type 'int'>
>>> print (int(list[0][0]))

12


8. 怎样对数据元素进行排序

>>> L = [('b',6),('a',1),('c',3),('d',4)]
>>> L.sort(key=lambda x:x[1]) 
>>> L
[('a', 1), ('c', 3), ('d', 4), ('b', 6)]
>>> L.sort(key=lambda x:x[0]) 
>>> L
[('a', 1), ('b', 6), ('c', 3), ('d', 4)]
>>> KK[]
  File "<stdin>", line 1
    KK[]
       ^
SyntaxError: invalid syntax
>>> KK=[]
>>> type (KK)
<type 'list'>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值