当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python zip()用法及代码示例


zip()的目的是映射多个容器的相似索引,以便可以将它们用作单个实体使用。

用法:
zip(*iterators)
参数:
Python iterables or containers ( list, string etc )
返回值:
Returns a single iterator object, having mapped values from all the
containers.
# Python code to demonstrate the working of  
# zip() 
  
# initializing lists 
name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ] 
roll_no = [ 4, 1, 3, 2 ] 
marks = [ 40, 50, 60, 70 ] 
  
# using zip() to map values 
mapped = zip(name, roll_no, marks) 
  
# converting values to print as set 
mapped = set(mapped) 
  
# printing resultant values  
print ("The zipped result is:",end="") 
print (mapped)

输出:


The zipped result is:{('Shambhavi', 3, 60), ('Astha', 2, 70),
('Manjeet', 4, 40), ('Nikhil', 1, 50)}

如何解压缩?
解压缩意味着将压缩后的值转换回原样。这是在“*”运算符的帮助下完成的。

# Python code to demonstrate the working of  
# unzip 
  
# initializing lists 
  
name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ] 
roll_no = [ 4, 1, 3, 2 ] 
marks = [ 40, 50, 60, 70 ] 
  
# using zip() to map values 
mapped = zip(name, roll_no, marks) 
  
# converting values to print as list 
mapped = list(mapped) 
  
# printing resultant values  
print ("The zipped result is:",end="") 
print (mapped) 
  
print("\n") 
  
# unzipping values 
namz, roll_noz, marksz = zip(*mapped) 
  
print ("The unzipped result:\n",end="") 
  
# printing initial lists 
print ("The name list is:",end="") 
print (namz) 
  
print ("The roll_no list is:",end="") 
print (roll_noz) 
  
print ("The marks list is:",end="") 
print (marksz)

输出:

The zipped result is:[('Manjeet', 4, 40), ('Nikhil', 1, 50), 
('Shambhavi', 3, 60), ('Astha', 2, 70)]


The unzipped result:
The name list is:('Manjeet', 'Nikhil', 'Shambhavi', 'Astha')
The roll_no list is:(4, 1, 3, 2)
The marks list is:(40, 50, 60, 70)

实际应用程序:可以说有许多可能的应用程序是使用zip压缩的,无论是学生数据库还是计分卡,还是需要组映射的任何其他实用程序。下面展示了一个记分卡的小例子。

# Python code to demonstrate the application of  
# zip() 
  
# initializing list of players. 
players = [ "Sachin", "Sehwag", "Gambhir", "Dravid", "Raina" ] 
  
# initializing their scores 
scores = [100, 15, 17, 28, 43 ] 
  
# printing players and scores. 
for pl, sc in zip(players, scores):
    print ("Player:  %s     Score:%d" %(pl, sc))

输出:

Player: Sachin     Score:100
Player: Sehwag     Score:15
Player: Gambhir     Score:17
Player: Dravid     Score:28
Player: Raina     Score:43



相关用法


注:本文由纯净天空筛选整理自manjeet_04大神的英文原创作品 zip() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。