Python 程序可同时迭代多个列表?
我们在此使用 .zip() 同时迭代多个列表。zip() 会获取任意数量的可迭代对象,并返回元组列表。第 i 个元素使用每个可迭代对象的第 i 个元素创建。
示例
L1=[1,2,3,4] L2=[‘aa’,’bb’,’cc’,’dd’] L=zip(L1,L2) Output [(1,’aa’),(2,’bb’),(3,’cc’),(4,’dd’)]
算法
Step 1: first create 3 user input list. Step 2 : use .zip() function. Step 3: print tuples.
示例代码
# To iterate over 3 lists using zip function
importitertools
A=list()
B=list()
C=list()
n = int(input("How many you data want to store??"))
print("Enter Roll no.")
for i in range(int(n)):
k=int(input(""))
A.append(k)
print("Enter Name ::")
for j in range(int(n)):
k1=input("")
B.append(k1)
print("Enter Age ::")
for j in range(int(n)):
k1=int(input(""))
C.append(k1)
print ("\niterating using zip")
for (a, b, c) in zip(A, B, C):
print (a, b, c)
输出
How many you data want to store??4 Enter Roll no. 56 89 67 34 Enter Name :: yui jkl vm dfg Enter Age :: 7 9 6 5 iterating using zip 56 yui 7 89 jkl 9 67 vm 6 34 dfg 5
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP