简体   繁体   English

与列表循环

[英]Making a loop with lists

I am new to Python and would like to create a print function that repeats itself for each item in a list (this is only an example my actual code will be for something else) 我是Python的新手,并且想创建一个打印函数,该函数会对列表中的每个项目重复一次(这只是一个示例,我的实际代码将用于其他功能)

cars.list = [Honda, Chevrolet, Suzuki, Ford]

price.list = [5600, 11500, 6600, 1020]

The prices and car lists are in the same order so Honda is $5600, Chevrolet is 11500 ect. 价格和车单顺序相同,因此本田为5600美元,雪佛兰为11500 ect。 I'd like it to run a loop for each of the cars that prints this: 我希望它为打印以下内容的每辆车运行一个循环:

while count in cars.list:
       print("The car type is" Honda/Chev ect. "The price is" 5600, 11500 ect"

I want it to repeat the loop for as many cars are in the cars.list , as I will add an option for the user to add more cars so the program cannot rely on knowing the specific cars in a list and copying the print statement for each one. 我希望它对cars.list中的cars.list汽车重复该循环,因为我将为用户添加一个选项以添加更多汽车,因此该程序不能依赖于了解列表中的特定汽车并复制打印语句每一个。 It needs to repeat the print statement for every car, replacing the price and car type each time with the next one in the list. 它需要为每辆汽车重复打印声明,每次用列表中的下一辆替换价格和类型。

You can use zip to associate the cars and prices together in an iterator of tuples, then iterate over those tuples while printing what you want. 您可以使用zip在元组的迭代器中将汽车和价格关联在一起,然后在打印所需内容时对这些元组进行迭代。

cars = ['Honda', 'Chevrolet', 'Suzuki', 'Ford']
prices = [5600, 11500, 6600, 1020]

for car, price in zip(cars, prices):
    print('The car type is {} and the price is {}.'.format(car, price))

Output: 输出:

The car type is Honda and the price is 5600.
The car type is Chevrolet and the price is 11500.
The car type is Suzuki and the price is 6600.
The car type is Ford and the price is 1020.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM