【问题标题】:Combine tuple and list into list-of-lists将元组和列表组合成列表列表
【发布时间】:2017-03-05 09:36:23
【问题描述】:

我对编程非常陌生,并试图将列表和元组组合成一个新列表:

  • goods 是商品的元组。
  • 每种商品都有对应的价格,随机生成并保存在列表中价格
  • 我想要一个名为 offer 的列表,为 goods 中的每个商品分配相应的价格值

我将非常感谢一个简单的解决方案,并简要说明为什么我的尝试只返回布料的值(我输入范围 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() 

【问题讨论】:

  • 我无法重现您的问题。
  • 范围和切片的右边界在 python 中被排除在外。所以 range(0,5) 的范围是 0 到 4 (含)。
  • 你真的是说你看到cloth的条目吗?那是我无法重现的。由于@PaulPanzer 给出的原因,确实发生了它停止在布料上。另一个问题 - 在您的循环中,您将在每次传递中创建一个新列表。如果您希望 offer 在循环完成后包含所有优惠的列表,则需要附加到不断增长的列表中。
  • 如果goodsprices有相同数量的元素,考虑使用zipfor good, price in zip(goods, prices): offer = [(good, price)]
  • {'commodity':price} 的字典比列表列表更符合 Python 风格。也更容易查找和迭代。 {commodity:price} for commodity in goods for price in prices}

标签: python list python-3.x nested-lists


【解决方案1】:

问题是range(0,5) 只会产生0,1,2,3,4,因为5 被排除在外。一个简单的解决方案是使用range(len(goods)),生成具有相同数量商品价值的范围:

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

或者,您可以使用zip 同时遍历两个列表:

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

这会产生一个元组的输出:

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

但可以用list(offer)转换成列表:

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

【讨论】:

  • zip(l1,l2)range(len(...)) 更好,也更简洁
  • 是的,看起来干净多了。
  • 实际上,{'commodity':price} 的字典比列表列表更符合 Python 风格。也更容易查找和迭代。 {commodity:price} for commodity in goods for price in prices}
  • 我认为{commodity:price for commodity,price in zip(goods,prices)} 可能更好。
  • 我也是这么想的。取决于OP的熟悉程度。非 Python 的人可能更喜欢前者,它使一切都变得明确。但是,两者都很棒。
猜你喜欢
  • 2017-09-16
  • 2020-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多