python 學習筆記之range函數和list

來源:互聯網
上載者:User
>>> range(0,2)[0, 1]>>> range(0,10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(0,10,2)[0, 2, 4, 6, 8]>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,5) #代表從1到5(不包含5)[1, 2, 3, 4]>>> range(1,5,2) #代表從1到5,間隔2(不包含5)[1, 3]>>> range(5) #代表從0到5(不包含5)[0, 1, 2, 3, 4]

range(a,b,-1)則恰好反過來,是從b到a,但是不包括b,包括a,有興趣可以試試

這樣就可以弄出一個list了。比如:

>>> p_list=range(8)>>> p_list[0, 1, 2, 3, 4, 5, 6, 7]

下面我們隊p_list進行一些操作,

添加項:append;

元素個數:count,注意它有一個參數

extend()方法只接受一個列表作為參數,並將該參數的每個元素都添加到原有的列表中。

pop:移除最末一項,或者移除指定索引的項

index:擷取某個值的位置,索引從0開始

insert:插入

remove:移除

reverse:翻轉

sort:排序

下面我們來測試一下:

產生k個不相等的1到n的隨機數:

import randomdef randDif(k,n):    if k>n:        return []    a=range(1,n+1)    random.shuffle(a)    return a[:k]#   調用方法randDif(5,10)

看看效果:

================================分割線====================================

>>> li = ['a', 'b', 'c']>>> li.extend(['d', 'e', 'f']) >>> li['a', 'b', 'c', 'd', 'e', 'f']>>> len(li)                    6>>> li[-1]'f'>>> li = ['a', 'b', 'c']>>> li.append(['d', 'e', 'f']) >>> li['a', 'b', 'c', ['d', 'e', 'f']]>>> len(li)                    4>>> li[-1]['d', 'e', 'f']

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.