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 = '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']
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 1. 这段时间小宝开始模仿各种语句,特别喜欢讲礼貌用语。 每天晚上洗完澡,他便像一条泥鳅一样滑出浴巾,满屋子跑,我...
    若儿织梦阅读 719评论 21 27
  • 文|CC宝贝儿 (一) “你是我心中最美的云彩……” “林总,您的电话响了。”工头老杨扯着嗓门向距离一米开外的迷彩...
    CC宝贝儿阅读 285评论 1 0
  • 看了新闻后,简直义愤填膺! 猥亵的可怕之处在于: 大人知道它的危害与后续的威力, 而儿童却全然不知。 她(他)幼小...
    尔萌阅读 268评论 0 0
  • 一、const与宏的区别: const简介:之前常用的字符串常量,一般是抽成宏,但是苹果不推荐我们抽成宏,推荐我们...
    CoderZS阅读 321评论 0 4