List 詳解


1 List

print ([1,24,76])
for i in [5,4,3,2,1]:
  print (i)
>>> 5 4 3 2 1 

fruit = 'Banana'
fruit[0] = 'b'
//String are not mutable
>>> Error!
// But we can manuplate with number

2. Using the Range Function

print (range(4))
>>> [0,1,2,3]

3.Concatenating Lists Using+

a = [1,2,3]
b = [4,5,6]
c = a+b
print (c)
>>> [1,2,3,4,5,6]

4 Building a List from Scratch

a = list()
a.append("book")
a.append(99)
print (a)
>>> ['book',99]

5. Is Something in a List

s = [1,2,3,4]
4 in s
>>> True

6. Split 函數(shù)

line = 'A lot       of  space'
etc = line.split()
print (etc)
>>> ['A','lot','of','space']
//這個(gè)函數(shù)有助于我們對(duì)于單詞的選取,對(duì)中文有幫助嗎?

line = 'first;second;third'
thing = line.split()
print (thing)
>>> ['first;second;third']

thing = line.split(';')
print (thing)
>>> ['first','second','third']
print(len(thing))
>>> 3

//一個(gè)例子
fhand = open('mbox.txt')
for line in fhand:
  line = line.rstrip() //刪除字符串末尾的指定內(nèi)容,默認(rèn)為空格
  if not line.startswith('From '): continue
    words = line.split()
    print(words[2])

// 一個(gè)截取郵箱后面的方法
line = '1141002@mail.sustc.edu.cn'
words = line.split('@')
print words[1]
>>> mail.sustc.edu.cn

7. Emenurate Methods

def double_odds(nums):
  for i, num in enumerate(num):
    if num%2==1:
      nums[i] = num * 2 

x = list(range(10))
double_odds(x)

x
>>> [0, 2, 2, 6, 4, 10, 6, 14, 8, 18]

8. List comprehension

squares = [n**2 for n in range(10) ]
>>> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

## Another way to make it more concise!
def count_negatives(nums):
    """Return the number of negative numbers in the given list.
    
    >>> count_negatives([5, -1, -2, 0, 3])
    2
    """
    n_negative = 0
    for num in nums:
        if num < 0:
            n_negative = n_negative + 1
    return n_negative

def count_negatives(nums):
    return len([num for num in nums if num < 0])

9.Short_Planets 條件選取,類似于SQL?

short_planets = [planet for planet in planets if len(planet) < 6]
short_planets
>>>['Venus', 'Earth', 'Mars']
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評(píng)論 0 10
  • 1. 這段時(shí)間小寶開始模仿各種語句,特別喜歡講禮貌用語。 每天晚上洗完澡,他便像一條泥鰍一樣滑出浴巾,滿屋子跑,我...
    若兒織夢(mèng)閱讀 841評(píng)論 22 28
  • 文|CC寶貝兒 (一) “你是我心中最美的云彩……” “林總,您的電話響了。”工頭老楊扯著嗓門向距離一米開外的迷彩...
    CC寶貝兒閱讀 305評(píng)論 1 0
  • 看了新聞后,簡(jiǎn)直義憤填膺! 猥褻的可怕之處在于: 大人知道它的危害與后續(xù)的威力, 而兒童卻全然不知。 她(他)幼小...
    爾萌閱讀 418評(píng)論 0 0
  • 一、const與宏的區(qū)別: const簡(jiǎn)介:之前常用的字符串常量,一般是抽成宏,但是蘋果不推薦我們抽成宏,推薦我們...
    CoderZS閱讀 369評(píng)論 0 4

友情鏈接更多精彩內(nèi)容