python中的内置函数zip其功能强大到令我发指,见如下代码段:
names = ["Lucas", "Mark", "David", "Kobe"]
ages = [21, 23, 53, 53]
# amazing again,it shucks me
print(list(zip(names, ages)))
# 当元素不对等时会怎样?
names.append("James")
print(names)
# 不会报错与上面结果输出一致,保持少数元素的集合
print(list(zip(names, ages)))
# 多个list的测试
teams = ["Rocket", "76ers", "Pacers", "Lakers"]
# 太强大,wow~
print(list(zip(names,ages,teams)))
# unzip 操作,这个操作的对象得注意,值得研究,用dictionary是不可以的
students = [("James", 32), ("Curry", "30"), ("Durant", "29")]
print(list(zip(*students)))
# amazing~ it's so cool
players = [("James", 32, "King"), ("Curry", "30", "Student"), ("Durant", "29", "Second")]
print(list(zip(*players)))
可以通过zip将两个list转换为dictionary,代码如下:
names = ["hello", "world", "hello", "python"]
# 多个变量对应多个list中的元素
for index, item in zip(range(4), names):
print(index, item)
# It's so cool
for index1, index2, item in zip(range(4), range(4), names):
print(index1,index2,item)
for index, item in enumerate(names):
print(index, item)
# 注意这个字典的关键字为dict
d = dict(zip(names,range(4)))
print(d)