python (选学) zip,列表

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43880084/article/details/102576242

假装会python

  • ## 暂时还不懂先存着

  • zip

list(zip(['a', 'b', 'c'], [1, 2, 3])) 将输出 [('a', 1), ('b', 2), ('c', 3)].
letters = ['a', 'b', 'c']
nums = [1, 2, 3]

for letter, num in zip(letters, nums):
    print("{}: {}".format(letter, num))
some_list = [('a', 1), ('b', 2), ('c', 3)]
letters, nums = zip(*some_list)

这样可以创建正如之前看到的相同 letters 和 nums 列表。

在这里插入图片描述

练习解决方案:组合坐标

x_coord = [23, 53, 2, -12, 95, 103, 14, -5]
y_coord = [677, 233, 405, 433, 905, 376, 432, 445]
z_coord = [4, 16, -6, -42, 3, -6, 23, -1]
labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"]

points = []
for point in zip(labels, x_coord, y_coord, z_coord):
    points.append("{}: {}, {}, {}".format(*point))

for point in points:
    print(point)

练习:将列表组合成字典

使用 zip 创建一个字典 cast,该字典使用 names 作为键,并使用 heights 作为值。

cast_names = ["Barney", "Robin", "Ted", "Lily", "Marshall"]
cast_heights = [72, 68, 72, 66, 76]


cast = dict(zip(cast_names, cast_heights))
print(cast)

练习:拆封元组

将 cast 元组拆封成两个 names 和 heights 元组。

cast = (("Barney", 72), ("Robin", 68), ("Ted", 72), ("Lily", 66), ("Marshall", 76))

names, heights = zip(*cast)
print(names)
print(heights)

练习:用 Zip 进行转置

使用 zip 将 data 从 4x3 矩阵转置成 3x4 矩阵。实际上有一个很酷的技巧。如果想不出答案的话,可以查看解决方案。

data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))

data_transpose = tuple(zip(*data))
print(data_transpose)

练习:Enumerate

使用 enumerate 修改列表 cast,使每个元素都包含姓名,然后是角色的对应身高。例如,cast 的第一个元素应该从 “Barney Stinson” 更改为 "Barney Stinson 72”。

cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"]
heights = [72, 68, 72, 66, 76]

for i, character in enumerate(cast):
    cast[i] = character + " " + str(heights[i])

print(cast)

列表

names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"]

first_names = [name.split()[0].lower() for name in names]
print(first_names)
['rick', 'morty', 'summer', 'jerry', 'beth']
练习解决方案:3 的倍数

multiples_3 = [x * 3 for x in range(1, 21)]
print(multiples_3)

练习:按得分过滤姓名

使用列表推导式创建一个 passed 的姓名列表,其中仅包含得分至少为 65 分的名字

scores = {
             "Rick Sanchez": 70,
             "Morty Smith": 35,
             "Summer Smith": 82,
             "Jerry Smith": 23,
             "Beth Smith": 98
          }

passed = [name for name, score in scores.items() if score >= 65]
print(passed)

猜你喜欢

转载自blog.csdn.net/weixin_43880084/article/details/102576242
今日推荐