The Seven Year Itch.

MENU

Python 列表解析 字典解析

May 11, 2018 • Read: 241 • Python

列表解析

数据格式:[2, -8, -10, -9, 4, 0, 6, -2, 3, 3]

from random import randint

range_num = [ randint(-10,10) for _ in range(10) ]

number = [ i for i in range_num if i >= 0 ]

print(number)

# filter 函数
number = filter(lambda x : x >= 0 ,range_num)
print(list(number))

OR

number = list(filter(lambda x : x >= 0 ,range_num))
print(number)

字典解析

数据格式: {'students-6': 63, 'students-3': 82, 'students-1': 92, 'students-4': 97, 'students-7': 81, 'students-2': 65, 'students-8': 71, 'students-0': 87, 'students-5': 58, 'students-9': 57}

from random import randint

range_num = { 'students-{}'.format(i):randint(50,100) for i in range(10) }
number = { k:v for k, v in range_num.items() if v >= 80 }
print(number)

#filter
number = filter(lambda x: x[1] >= 90 , range_num.items())
print(dict(number))
or

number = dict(filter(lambda x: x[1] >= 90 , range_num.items()))
print(number)
Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code