【问题标题】:Tuples, list and Dictionaries code to print rows and columns用于打印行和列的元组、列表和字典代码
【发布时间】:2021-05-22 00:02:58
【问题描述】:

我正在尝试编写一个基于元组、列表和字典的小代码。我有下面的代码,但我有以下错误:

  1. 它只需要“折扣和商店产品”的值,但我还需要它来考虑折扣。

  2. 当它打印时,它以如下形式打印。

    {'1': 'Tango', '2': 'Ice cream', '3': 'Gum rolls', '4': 'Wet Napkins', '5': 'Catfood', '6': 'DoogFood'} ['none', 'none', 'none', '10%', '5%', '5%']
    
    {'T': ['1'], 'a': ['1', '2', '4', '5'], 'n': ['1', '4'], 'g': ['1', '6'], 'o': ['1', '3', '5', '5', '6', '6', '6', '6'], 'I': ['2'], 'c': ['2', '2'], 'e': ['2', '2', '4'], ' ': ['2', '3', '4'], 'r': ['2', '3'], 'm': ['2', '3'], 'G': ['3'], 'u': ['3'], 'l': ['3', '3'], 's': ['3', '4'], 'W': ['4'], 't': ['4', '5'], 'N': ['4'], 'p': ['4'], 'k': ['4'], 'i': ['4'], 'C': ['5'], 'f': ['5'], 'd': ['5', '6'], 'D': ['6'], 'F': ['6']}
    
  3. 忽略代码的反转部分。我正在试验 python 的那部分,但如果你有任何建议可以让它变得更好,我想听听。

我希望代码像这样打印。

1 Tango .40 none
2 Ice cream .25 none   **OR SIMILAR FORM**
3 Gum rolls .50 none.  

每次我尝试添加价格时,它都会给我一条错误消息: TypeError: float() argument must be a string or a number, not 'tuple'

谁能指出正确的方向来解决这个问题,请简要说明。

discount = ["none", "none", "none", "10%", "5%", "5%"]
price = float((.40, 0.25, .50, 3.75, .68, .85))
store_product = {
    "1": "Tango",
    "2": "Ice cream",
    "3": "Gum rolls",
    "4": "Wet Napkins",
    "5": "Catfood",
    "6": "DoogFood",
}


print(store_product, price, discount)
print("")


def invert(d):
  inverse = dict()
  for key in d:
    val = d[key]
    for item in val:
      if item not in inverse:
        inverse[item] = [key]
      else:
        inverse[item].append(key)
  return inverse 


inverted_product = invert(store_product)
print(inverted_product)
    

有没有可能做这样的事情,还是我想多了?

【问题讨论】:

    标签: python list dictionary tuples


    【解决方案1】:

    如果你想同时打印discountpricestore_product,你可以这样做:

    discount = ["none", "none", "none", "10%", "5%", "5%"]
    price = (0.40, 0.25, 0.50, 3.75, 0.68, 0.85)
    store_product = {
        "1": "Tango",
        "2": "Ice cream",
        "3": "Gum rolls",
        "4": "Wet Napkins",
        "5": "Catfood",
        "6": "DoogFood",
    }
    
    for k, v in store_product.items():
        k = int(k)
        print(v, price[k - 1], discount[k - 1])
    

    打印:

    Tango 0.4 none
    Ice cream 0.25 none
    Gum rolls 0.5 none
    Wet Napkins 3.75 10%
    Catfood 0.68 5%
    DoogFood 0.85 5%
    

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2012-07-15
      • 2023-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多