本文介绍了如何将两个列表一起添加以创建一个最终列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有两个名单,一个名为免费小时,一个名为hoursbookedlist,我想将它们一起添加到名为总小时数的列表中 #Imports Time 随机导入 导入时间 freehours = [] nameslist = [] hoursbookedlist = [] totalhoursbooked = [] 适用于范围内的学生(7): name =输入(输入学生姓名) hoursbooked = int(输入(输入为学生预订的小时数)) while(hoursbooked< 10): 打印(请重新输入预订的小时数:) hoursbooked = int(输入(请为stundent1预订的小时数) ) 如果小时预订> 10和小时册< 15: freehours.append(1) elif int(hoursbooked> = 15): freehours.append(2) nameslist.append(姓名) hoursbookedlist.append(小时预订) totalhoursbooked = freehours + hoursbookedlist print(student \t hoursbooked \t freehours \t totalhoursbooked) for i in range(7): print(nameslist [i],\t,\ t,hoursbookedlist [i],\ t ,\ t,freehours [i],\t,\t,totalhoursbooked [i]) 我是什么尝试过: 我试过做totalhoursbooked = freehourslist + hoursbookedlist 解决方案 然后列表函数将此迭代器转换为列表。 您还可以使用列表理解 [ ^ ]和 zip功能 [ ^ ]。 totalhoursbooked = [a + b for a,b in zip(freehourslist,hoursbookedlist)] Z. ip创建一个迭代器,它聚合来自作为参数传递的每个迭代的元素。 (如果您将 zip 返回值转换为列表,您将看到一个元组列表,其中每个元组包含来自freehourslist的元素以及相应的hoursbookedlist元素)。 I have two lists one called free hours and one called hoursbookedlist and I want to add them together to a list called total hours booked#Imports Timeimport randomimport timefreehours = []nameslist = []hoursbookedlist = []totalhoursbooked = []for student in range(7): name = input("Enter students name ") hoursbooked = int(input("Enter number of hours booked for the students ")) while (hoursbooked <10): print("Please re-enter number of hours booked: ") hoursbooked = int(input("please the number of hours that have been booked for stundent1 ")) if hoursbooked > 10 and hoursbooked < 15: freehours.append(1) elif int(hoursbooked >=15): freehours.append(2) nameslist.append(name) hoursbookedlist.append(hoursbooked)totalhoursbooked = freehours + hoursbookedlistprint ("student \t hoursbooked \t freehours \t totalhoursbooked")for i in range(7): print(nameslist[i],"\t","\t",hoursbookedlist[i],"\t","\t",freehours[i],"\t","\t", totalhoursbooked[i])What I have tried:I tried just doing totalhoursbooked = freehourslist + hoursbookedlist 解决方案 Then the list function transforms this iterator into a list.You can also use a combination of list comprehension[^] and the zip function[^].totalhoursbooked = [a + b for a, b in zip(freehourslist, hoursbookedlist)]Zip makes an iterator that aggregates elements from each of the iterables passed as arguments. (If you'd convert the zip return value to a list, you'd see a list of tuples where each tuple contains an element from freehourslist with the corresponding hoursbookedlist element). 这篇关于如何将两个列表一起添加以创建一个最终列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-21 22:52