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 函数

line = 'A lot       of  space'
etc = line.split()
print (etc)
>>> ['A','lot','of','space']
//这个函数有助于我们对于单词的选取,对中文有帮助吗?

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

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

//一个例子
fhand = open('mbox.txt')
for line in fhand:
  line = line.rstrip() //删除字符串末尾的指定内容,默认为空格
  if not line.startswith('From '): continue
    words = line.split()
    print(words[2])

// 一个截取邮箱后面的方法
line = '[email protected]'
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']

你可能感兴趣的:(List 详解)