[python] List Comprehension

来源:互联网 发布:淘宝特卖女装清仓 编辑:程序博客网 时间:2024/05/10 21:27

  • List Comprehension
  • Set comprehension
  • Dictionary Comprehension

1. List Comprehension

List comprehension is to creat a new list quickly. Example:

# list comprehension>>> mylist = [1,2,2,3,4,4]>>> newlist1 = [x**2 for x in mylist] #square>>> newlist1[1, 4, 4, 9, 16, 16]>>> newlist2 = [x+1 for x in mylist if x%2==0]>>> newlist2[3, 3, 5, 5]

2. Set comprehension

The difference of list and set is that elements in set are unique while list not. Example:

# set comprehension>>> newset = {x+1 for x in mylist}>>> newsetset([2, 3, 4, 5])

an alternative solution is

>>> newlist3 = [x+1 for x in mylist]>>> newlist3[2, 3, 3, 4, 5, 5]>>> newset1 = set(newlist3)>>> newset1set([2, 3, 4, 5])

3. Dictionary Comprehension

Example:

# dictionary comprehension>>> newdict = {x:x-1 for x in mylist}>>> newdict{1: 0, 2: 1, 3: 2, 4: 3}
0 0
原创粉丝点击