合并来自2个列表的数据

2024-06-02 21:00:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手。我有两个列表,我想从title中获取一个元素,从price中获取一个元素,并将其保存在一个文件mean.txt中 标题

['Cappuccino with Milk Chocolate Cookie', 'Cappuccino with Double Chocolate Cookie', 'Latte with Milk Chocolate Cookie', 'Latte with Double Chocolate Cookie', 'McFizz Guava', 'Date Pie', 'Spicy McCrispy Deluxe - Regular Meal', 'McChicken - Regular Meal', 'Curly Fries', 'Salted Caramel Shake']

价格:

['Rs 288', 'Rs 288', 'Rs 288', 'Rs 288', 'Rs 159', 'Rs 195', 'Rs 416', 'Rs 416', 'Rs 239', 'Rs 239']

期望输出: 在mean.txt文件中

Title : Cappuccino with Milk Chocolate Cookie
Price : Rs 288
#space
Title : Cappuccino with Double Chocolate Cookie
Price : Rs 288 
....

比如抓住标题索引(0)上的一个元素,并将其与价格索引(0)相结合


Tags: 文件txt元素标题cookiewithmeandouble
3条回答

正如其他人提到的,zip()函数特别有用。在python中使用.format()link)和writing out to a file也很重要

l1 = ['Cappuccino with Milk Chocolate Cookie', 'Cappuccino with Double Chocolate Cookie', 'Latte with Milk Chocolate Cookie', 'Latte with Double Chocolate Cookie', 'McFizz Guava', 'Date Pie', 'Spicy McCrispy Deluxe - Regular Meal', 'McChicken - Regular Meal', 'Curly Fries', 'Salted Caramel Shake']
l2 = ['Rs 288', 'Rs 288', 'Rs 288', 'Rs 288', 'Rs 159', 'Rs 195', 'Rs 416', 'Rs 416', 'Rs 239', 'Rs 239']

outstring = ''
for elem1, elem2 in zip(l1, l2):
    s = 'Title : {}\nPrice : {}\n\n'.format(elem1, elem2)
    outstring += s

fn = 'meal.txt'
with open(fn, 'w') as f:
    f.write(outstring) 
Title = ['Cappuccino with Milk Chocolate Cookie', 'Cappuccino with Double, Chocolate Cookie', 'Latte with Milk Chocolate Cookie', 'Latte with Double', 'Chocolate Cookie', 'McFizz Guava', 'Date Pie', 'Spicy McCrispy Deluxe - Regular Meal', 'McChicken - Regular Meal', 'Curly Fries', 'Salted Caramel Shake']

Price = ['Rs 288', 'Rs 288', 'Rs 288', 'Rs 288', 'Rs 159', 'Rs 195', 'Rs 416', 'Rs 416', 'Rs 239', 'Rs 239']

data_dict = dict(zip(Title, Price))  

for title, price in data_dict.items():  
    print("Title : {}\nPrice : {}\n".format(title, price)) 

组合两个列表的最简单方法是zip

for title, price in zip(titles, prices):
   print(f'Title : {title}\nPrice : {price}\n')

相关问题 更多 >