12 練習題:生成器 列表推導式 內置函數Ⅰ

# 用列表推導式作下列小題
# 1.過濾掉長度小於3的字符串列表,並將剩下的轉換成大寫字母

l1 = ['string', 'str', 'st']
li = [i.upper() for i in l1 if len(i) < 3]



# 2.求(x,y)其中x是0-5之間的偶數,y是0-5之間的奇數組成的元祖列表
li = [(x, y) for x in range(0, 6, 2) for y in range(1, 6, 2)]
print(li)



# 3.求M中3,6,9組成的列表M = [[1,2,3],[4,5,6],[7,8,9]]
M = [[1,2,3],[4,5,6],[7,8,9]]
li = [i[2] for i in M]
print(li)



# 4.求出50之內能被3整除的數的平方,並放入到一個列表中。
li = [i ** 2 for i in range(1, 50) if i % 3 == 0]
print(li)



# 5.構建一個列表:['python1期', 'python2期', 'python3期', 'python4期', 'python6期', 'python7期', 'python8期', 'python9期', 'python10期']
li = [f'python{i}期' for i in range(1, 11)]
print(li)



# 6.構建一個列表:[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
li = [(i, i + 1) for i in range(6)]
print(li)



# 7.構建一個列表:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
li = [i for i in range(0, 20, 2)]
print(li)



# 8.有一個列表l1 = ['alex', 'WuSir', '老男孩', '太白']將其構形成這種列表['alex0', 'WuSir1', '老男孩2', '太白3']
l1 = ['alex', 'WuSir', '老男孩', '太白']
li = [l1[i] + str(i) for i in range(len(l1))]
print(li)



# 9.有如下數據類型:
# x = {'name':'alex',
#      'Values':[{'timestamp':1517991992.94,'values':100,},
#                {'timestamp': 1517992000.94,'values': 200,},
#             {'timestamp': 1517992014.94,'values': 300,},
#             {'timestamp': 1517992744.94,'values': 350},
#             {'timestamp': 1517992800.94,'values': 280}],}
# 將上面的數據經過列表推導式轉換成下面的類型:[[1517991992.94, 100], [1517992000.94, 200], [1517992014.94, 300], [1517992744.94, 350], [1517992800.94, 280]]
x = {'name':'alex',
     'Values':
         [{'timestamp':1517991992.94,'values':100,},
          {'timestamp': 1517992000.94,'values': 200,},
          {'timestamp': 1517992014.94,'values': 300,},
          {'timestamp': 1517992744.94,'values': 350},
          {'timestamp': 1517992800.94,'values': 280}],
     }
li = [[x['Values'][i]['timestamp'], x['Values'][i]['values']] for i in range(len(x['Values']))]
print(li)



# 10.用列表完成笛卡爾積
# 什麼是笛卡爾積? 笛卡爾積就是一個列表,列表裏面的元素是由輸入的可迭代類型的元素對構成的元組,所以笛卡爾積列表的長度等於輸入變量的長度的乘積。
magnitude_1 = input('PLS input magnitude 1:\n').split()
magnitude_2 = input('PLS input magnitude 2:\n').split()
cartesian = [(x, y) for x in magnitude_1 for y in magnitude_2]
print(cartesian)



# 11. 構建一個列表,列表裏面是三種不一樣尺寸的T恤衫,每一個尺寸都有兩個顏色(列表裏面的元素爲元組類型)。
# colors = ['black', 'white']
# sizes = ['S', 'M', 'L']
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
li = [(color, size) for color in colors for size in sizes]
print(li)



# 12. 構建一個列表,列表裏面的元素是撲克牌除去大小王之後,全部的牌類(列表裏面的元素爲元組類型)。
# l1 = [('A','spades'),('A','diamonds'), ('A','clubs'), ('A','hearts')......('K','spades'),('K','diamonds'), ('K','clubs'), ('K','hearts') ]
l1 = ['A'] + [str(i) for i in range(2, 11)] + list('JQK')
l2 = ['spades', 'diamonds', 'clubs', 'hearts']
li = [(l1[i], l2[j]) for i in range(len(l1)) for j in range(len(l2))]
print(li)



# 13.簡述一下yield 與yield from的區別。
# yield 定義生成器函數
# yield from 也是定義生成器函數,可是它能夠將列表變成迭代器返回



# 14.看下面代碼,可否對其簡化?說說你簡化後的優勢?
# def chain(*iterables):
#     for it in iterables:
#         for i in it:
#             yield i
#
#
# g = chain('abc', (0, 1, 2))
# print(list(g))  # 將迭代器轉化成列表


# 優化內層循環,提升效率
def chain(*iterables):
    for it in iterables:
        yield from it

g = chain('abc', (0, 1, 2))
print(list(g))



# 15.看代碼求結果(面試題):
# v = [i % 2 for i in range(10)]
# print(v)
# v = (i % 2 for i in range(10))
# print(v)
# for i in range(5):
# 	print(i)
# print(i)

# result:
# [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
# <generator object <genexpr> at 0x000002A8A63CD0F8>
# 0
# 1
# 2
# 3
# 4
# 4



# 16.看代碼求結果:(面試題)***
def demo():
    for i in range(4):
        yield i

g = demo()  # <generator object demo at 0x000001F272E146D0>
g1 = (i for i in g)  # <generator object <genexpr> at 0x0000021B6AB8D0F8>
g2 = (i for i in g1)  # <generator object <genexpr> at 0x0000023A615547D8>
print(list(g1))  # print(list((i for i in demo())))
print(list(g2))  # generator 'g1' StopIteration
# result:
# [0, 1, 2, 3]
# []



# 17.看代碼求結果:(面試題)*****
def add(n, i):
    return n + i

def test():
    for i in range(4):
        yield i

g = test()
for n in [1, 10]:
    g = (add(n, i) for i in g)
print(list(g))

# result:
# [20, 21, 22, 23]

# 題目能夠理解爲:
# g = test()
# n = 1
# g = (add(n, i) for i in g)
# n = 10
# g = (add(n, i) for i in g)
# print(list(g))  # list((add(10, i) for i in (add(10, i) for i in test))))
# 這時候纔開始執行g迭代器兩次,但是這時候n已經定義爲10,因此至關於在n爲10時讀取迭代器
相關文章
相關標籤/搜索