美文网首页
List 详解

List 详解

作者: 瞬间流星 | 来源:发表于2018-05-17 11:28 被阅读0次

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']

相关文章

  • FreeMarker | 笔记篇

    java中Freemarker list指令详解 java中Freemarker if else指令详解 java...

  • Java遍历ArrayList,Map和Set四种方法对比

    1.1 List 1.1.1 遍历ArrayList 1.1.2 数组与List之间相互转换的方法详解 List转...

  • List 详解

    1 List 2. Using the Range Function 3.Concatenating Lists ...

  • List详解

    https://www.jianshu.com/p/63b01b6379fb ArrayList和LinkedLi...

  • List

    出处:Java list的用法排序及遍历详解 List 不能实例化,因为list是一个接口,可以添加任何类型对象可...

  • Flutter/Dart - 集合类型List、Map详解

    List详解,List里面常用的属性和方法 List的定义 第一种定义方法 第二种定义方法 List里面的方法属性...

  • List详解(ArrayList、LinkedList、Vect

    List详解 Arraylist: Object数组 LinkedList: 双向链表(JDK1.6之前为循环链表...

  • client list 详解

    节选自《redis开发与运维》 先来看一段client list的执行结果 输出结果的每一行代表一个客户端的信息,...

  • Browser list详解

    请移步到我的Blog,获得更好的阅读体验!本文的链接请点这里 browserlist是什么? browserlis...

  • SwiftUI:List详解

    1. 隐藏/取消List的分割线 iOS 13.0+ (全局效果) iOS 14.0+ iOS 15.0+ 其他...

网友评论

      本文标题:List 详解

      本文链接:https://www.haomeiwen.com/subject/voomdftx.html