简体   繁体   English

将元组和列表合并到列表列表中

[英]Combine tuple and list into list-of-lists

I'm very new to programming and trying to combine a list and tuple into a new list: 我对编程非常陌生,并尝试将一个列表和元组合并到一个新列表中:

  • goods is a tuple of commodities. 商品是商品的元组。
  • Each commodity has a corresponding price, generated at random and saved in the list prices 每个商品都有一个对应的价格,随机生成并保存在标价中
  • I want a list called offer assigning the corresponding price value to each commodity from goods 我希望有一个列表称为提供相应的价格值分配给从商品每件商品

I'd be very grateful for a simple solution and also a brief explanation why my attempt only returns a value for cloth (I entered range 0:5 but it seems just to return element 4, cloth and its price) 我将非常感谢您提供一个简单的解决方案,并简要说明了为什么我的尝试仅返回布的值(我输入的范围是0:5,但似乎只是返回元素4,布及其价格)

import random

goods = ("Silk", "Gems", "Wool", "Hide", "Cloth", "Iron")

def set_prices ():

    price_s = random.randrange(180,300)
    price_g = random.randrange(250,800)
    price_w = random.randrange(1,5)
    price_h = random.randrange(5,18)
    price_c = random.randrange(20,50)
    price_i = random.randrange(50,150)

    prices = [price_s,price_g,price_w,price_h,price_c,price_i]

    for n in range (0,5):
        offer = [(goods[n],prices[n])] 
        print (offer)

set_prices() 

The problem is that range(0,5) will only produce 0,1,2,3,4 , as the 5 is excluded. 问题在于range(0,5)仅会产生0,1,2,3,4 ,因为排除了5 An easy solution is to use range(len(goods)) , to produce a range with the same number of values of goods: 一个简单的解决方案是使用range(len(goods)) ,以产生具有相同数量商品价值的范围:

for n in range(len(goods)):
    ...

Alternatively, you could use zip to iterate through both lists simultaneously: 另外,您可以使用zip来同时遍历两个列表:

for offer in zip(goods,prices):
    print(offer)

This produces output as a tuple: 这产生的输出为元组:

('Silk', 276)
('Gems', 486)
...

but can be converted to a list with list(offer) : 但是可以使用list(offer)转换为列表:

['Silk', 188]
['Gems', 620]
['Wool', 2]
['Hide', 14]
['Cloth', 38]
['Iron', 130]

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

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