users=int(input("enter the number of users whose data you want to enter"))
List1=[]
List2=[]
List3=[]
username=[]
copied_list=[]
for i in range(1,users+1):
print(f"Enter first name of user{i}")
List1.append(input())
print(f"Enter last name of user{i}")
List2.append(input())
print(f"Enter birth year of user{i}")
List3.append(input())
Full_Details=zip(List1,List2,List3)
print("Before for loop")
print(list(Full_Details))
for i in Full_Details:
username.append(i[0][0]+i[1]+i[2][-2:])
print("After for loop")
print(list(Full_Details))
**如果我尝试在 for 循环之前转换为元组后打印 Full_details ,它会准确地打印列表,但如果我尝试在 for 循环之后打印它,它会打印空列表。它背后的逻辑是什么。
我还无法发布输出图像
但结果是这样的
输入您要输入其数据的用户数量2
输入用户 1 的名字
严酷
输入用户 1 的姓氏
桑湾
输入用户1的出生年份
2003
输入用户 2 的名字
开发
输入用户2的姓氏
夏尔马
输入用户2的出生年份
2004年
在 for 循环之前
[('严酷', '桑万', '2003'), ('开发', '夏尔马', '2004')]
for循环之后
[]
**
这是因为Python中的zip对象是一个迭代器。迭代器是一个记住遍历位置的对象。当您使用 list() 函数一次将 zip 对象转换为列表时,迭代器将到达末尾。再次调用 list() 函数不会生成更多元素,因此返回一个空列表。
在您的代码中,行 print(list(Full_Details)) 已经完全遍历了 zip 对象 Full_Details 一次。因此,当您再次调用 print(list(Full_Details)) 时,它会返回一个空列表。
如果想多次使用zip对象生成的元素,可以在创建zip对象后立即将其转换为列表,如下代码所示:
Full_Details = list(zip(List1,List2,List3))
这样,Full_Details就变成了一个列表,你可以多次遍历它,每次都得到相同的结果。
users=int(input("enter the number of users whose data you want to enter: "))
List1=[]
List2=[]
List3=[]
username=[]
copied_list=[]
for i in range(1,users+1):
print(f"Enter first name of user{i}: ", end="")
List1.append(input())
print(f"Enter last name of user{i}: ", end="")
List2.append(input())
print(f"Enter birth year of user{i}: ", end="")
List3.append(input())
# Full_Details=zip(List1,List2,List3)
Full_Details = list(zip(List1,List2,List3))
print("Before for loop")
print(list(Full_Details))
print(Full_Details)
for i in Full_Details:
username.append(i[0][0]+i[1]+i[2][-2:])
print("After for loop")
print(list(Full_Details))
print(Full_Details)