python常见问题

来源:互联网 发布:济南软件开发balkwill 编辑:程序博客网 时间:2024/06/03 22:43

1、list和tuple相互转换

    Python中,tuple和list均为内置类型;

    以list作为参数将tuple类初始化,将返回tuple类型

          tuple([1,2,3]) #list转换为tuple

    以tuple作为参数将list类初始化,将返回list类型

          list((1,2,3)) #tuple转换为list
2、eclipse中使用pydev解决: unresolved import

     在project(watip)右击打开菜单 ->选择properties->选择"PyDev-Interpreter/Grammar"->点击链接"Click here to configure an interpreter not listed." -> 在"Libraries"tab内,点击"new folder",加入util的上引目录"src"的路径->点击"ok",记得重启eclipse.


3、判断Boolean类型,采用is关键字

            if head is True:                return data[1:]
4、list操作

1)、创建列表并给它赋值
创建一个列表就像给一个变量赋值一样的简单,你也可以手工写一个列表(空的或者有值的都行)然后赋值给一个变量,列表是由方括号([ ])来定义的,你也可以使用工厂方法list()来创建它。
Java代码  收藏代码

    >>>aList = [123, 'abc', 4.56, ['inner', 'list'], 7-9j]  
    >>>anotherList = [None, 'something to see here']  
    >>>print(aList)  
    [123, 'abc', 4.56, ['inner', 'list'], (7-9j)]  
    >>> print(anotherList)  
    [None, 'something to see here']  
    >>> aListThatStartedEmpty = []  
    >>> print(aListThatStartedEmpty)  
    []  
    >>> list('foo')  
    ['f', 'o', 'o']  


2)、访问列表中的值
列表的切片操作就像字符串中一样:切片操作符([ ])和索引值或者索引值范围一起使用。
Java代码  收藏代码

    >>> aList[0]  
    123  
    >>> aList[1:4]  
    ['abc', 4.56, ['inner', 'list']]  
    >>> aList[:3]  
    [123, 'abc', 4.56]  
    >>> aList[3][1]  
    'list'  


3)、更新列表
你可以通过在等号左边指定一个索引或者索引范围的方式来更新一个或几个元素,也可以使用append()方法来追加元素到列表中去。
Java代码  收藏代码

    >>> aList  
    [123, 'abc', 4.56, ['inner', 'list'], (7-9j)]  
    >>> aList[2]  
    4.56  
    >>> aList[2] = 'float replacer'  
    >>> aList  
    [123, 'abc', 'float replacer', ['inner', 'list'], (7-9j)]  
    >>> anotherList.append ("hi, i'm new here")  
    >>> print(anotherList)  
    [None, 'something to see here', "hi, i'm new here"]  
    >>> aListThatStartedEmpty.append ('not empty anymore')  
    >>> print(aListThatStartedEmpty)  
    ['not empty anymore']  


4)、删除列表中的元素或者列表本身
要删除列表中的元素,如果你确切知道要删除元素的索引可以使用del语句,否则可以使用remove()方法。
Java代码  收藏代码

    >>> aList  
    [123, 'abc', 'float replacer', ['inner', 'list'], (7-9j)]  
    >>> del aList[1]  
    >>> aList  
    [123, 'float replacer', ['inner', 'list'], (7-9j)]  
    >>> aList.remove (123)  
    >>> aList  
    ['float replacer', ['inner', 'list'], (7-9j)]  


你还可以通过pop()方法来删除并从列表中返回一个特定对象。
一般来说,程序员不需要去删除一个列表对象。列表对象出了作用域(比如程序结束,函数调用完成等等)后它会自动被析构。如果你想明确的删除整个列表,你可以使用del语句:
del aList

5)、列表常用的其他内置函数
除了以上的基本操作外,在python中还有一些其他的内置函数:
append:向列表中添加一个对象
count:返回一个对象在列表中出现的次数
extend:把一个列表添加到原有的一个列表里面
index:返回一个对象在列表中的序号
insert:在索引值位置插入对象
pop:删除并返回指定位置的对象,默认是一个对象
reserve:原地翻转列表
sort:对列表中的元素排序


1 0
原创粉丝点击