# 小白的Python 学习笔记（八）推导式详解

• 列表推导式（list comprehensions）
• 字典推导式（dict comprehensions）
• 集合推导式（set comprehensions）

### 列表推导式（list comprehensions）

• [ expression for item in list if conditional ] 简单来说，遍历一个list，得到每一个元素item，我们相对item进行哪些操作，写在expression里就可以，如果对筛选有什么条件，可以放在if后面

```h_letters = []
for letter in 'human':
h_letters.append(letter)

print(h_letters)![enter image description here](https://user-gold-cdn.xitu.io/2019/6/14/16b55313e2dd1a43?w=404&h=133&f=png&s=31177)

Out：['h', 'u', 'm', 'a', 'n']

```h_letters = [ letter for letter in 'human' ]
print( h_letters)

Out: ['h', 'u', 'm', 'a', 'n']

```h_letters = [ letter.upper() for letter in 'human' ]
print( h_letters)

Out: ['H', 'U', 'M', 'A', 'N']

```result = [num for num in range(-20,20)
if num %3==0 and num > 0]

print(result)       #多个条件可以用and连接

Out: [3, 6, 9, 12, 15, 18]

### 字典推导式（dict comprehensions )

• { key:value for key,value in existing_data_structure }

```person = {'name':'xiaobai','city':'paris'}
person_reverse = {v:k for k,v in person.items()}   #简单互换key和value的值即可

print(person_reverse)
Out: {'xiaobai': 'name', 'paris': 'city'}

```nums = {'a':10,'b':20,'A':5,'B':3,'d':4}
num_frequency  = {k.lower():nums.get(k.lower(),0) + nums.get(k.upper(),0)
for k in nums.keys() }

print(num_frequency)

Out: {'a': 15, 'b': 23, 'd': 4}

```fruit = ['apple','banana','organge','mango','peach']

fruit_len = {f:len(f) for f in fruit}
print(fruit_len)

Out：{'apple': 5, 'banana': 6, 'organge': 7, 'mango': 5, 'peach': 5}

```fruit = ['apple','organge','banana','mango','peach']

fruit_positon = {v:i for i,v in enumerate(fruit)}
print(fruit_positon)

Out: {'apple': 0, 'organge': 1, 'banana': 2, 'mango': 3, 'peach': 4}

### 集合推导式（Set comprehensions）

• { expression for item in Sequence if conditional }

```names = [ 'Bob', 'JOHN', 'alice', 'bob', 'ALICE', 'James', 'Bob','JAMES','jAMeS' ]
names_standard = { n[0].upper()+n[1:].lower() for n in names}

print(names_standard)
Out: {'John', 'Bob', 'James', 'Alice'}

### 简单实战

```with open('dictionary.txt') as dictionary_file:
words = (line.rstrip() for line in dictionary_file)
words_over_five_letters = [w for w in words if len(w)>5 ]

```reversed_words ={
word[::-1]
for word in words_over_five_letters
}

```reversible_words = [
word
for word in words_over_five_letters
if word in reversed_words
]

for word in reversible_words[0:20]:
print(word)

Out：
abrood
agenes
amaroid
amunam
animal
animes
bruted
darter
decart
decurt
deedeed
deflow
degami
degener
degged
deified
deifier
deliver
denier

```with open('dictionary.txt') as dictionary_file:
words = (line.rstrip() for line in dictionary_file)
words_over_five_letters = [w for w in words if len(w)>5 ]

reversed_words ={
word[::-1]
for word in words_over_five_letters
}

reversible_words = [
word
for word in words_over_five_letters
if word in reversed_words
]

for word in reversible_words[0:20]:
print(word)