【问题标题】:Creating dictionaries with keys based on user input使用基于用户输入的键创建字典
【发布时间】:2018-09-10 22:48:10
【问题描述】:
Cow_id_list = []

Herd_Size = int(input("Enter the size of the herd."))

for x in range(Herd_Size):
    Cow_id = int("Enter a unique 3 digit ID tag for cow",x+1)
    Cow_id_list.append(Cow_id)

print("Initiating yield entry...")

用户输入一个整数 (n),该整数将存储在变量 Herd_Size 中。如何创建具有相同(n)个键和我们选择的名称的字典? 键值的名称将是 ID 标签

【问题讨论】:

  • 那么dict的键和值应该是什么?它们都是用户输入吗?
  • 键应该是奶牛的ID标签,值应该是用户输入的牛奶产量。
  • 但是ID标签也是用户输入的?
  • 是的,但我对如何在字典上创建 (n) 个键感到困惑...键值的名称将是 ID

标签: python dictionary


【解决方案1】:

不确定为什么需要创建具有特定键数的字典。您可以只要求用户输入 ID 和 yield 并将其放入字典中。

如果你有 10 头奶牛,你不会有 15 个 ID 和产量。

def add_cow_info():
    add_info = str(input("input cow id and yield?: (y/n)")
    if add_info == "y":
        return True
    elif add_info == "n":
        return False


def main():
    cow_yield = {}
    input_cow = True
    while input_cow():
        ID = str(input("Enter ID: ")) #if the ID is 001, or 010, the result
                                      # will be 1, 10, respectively. 
                                      #Generally keys should be strings anyways.
        _yield = int(input("Enter yield: "))
        cow_yield[ID] = _yield

    return cow_yield

【讨论】:

    【解决方案2】:

    jpp 的方式可能更好,因为您可以同时获得收益和 ID。但是,如果你想保持你的结构,你可以这样做:

    Cow_id_list = []
    
    Herd_Size = int(input("Enter the size of the herd."))
    
    for x in range(Herd_Size):
        Cow_id = int(input("Enter a unique 3 digit ID tag for cow"))
        Cow_id_list.append(Cow_id)
    
    print("Initiating yield entry...")
    
    d = {}
    for i in Cow_id_list:
        y = float(input("Enter yielf for cow {}: ".format(i)))
        d[i] = y
    

    这里发生的事情是,您将d 作为一个空字典启动,然后遍历您的奶牛 ID,一一获取产量,然后为每头奶牛添加一个键,并将相应的产量作为值字典d

    【讨论】:

      【解决方案3】:

      这是一种方式。

      Cow_id_list = []
      Yield_list = []
      
      Herd_Size = int(input("Enter the size of the herd."))
      
      for x in range(Herd_Size):
          Cow_id = int(input("Enter a unique 3 digit ID tag for cow"))
          Yield = int(input("Enter yield for {0}".format(Cow_id)))
          Cow_id_list.append(Cow_id)
          Yield_list.append(Yield)
      
      d = dict(zip(Cow_id_list, Yield_list))
      

      说明

      • 要求Cow_id 输入整数,方法与Herd_Size 相同。
      • Yield 执行相同的操作。创建一个Yield_list,例如Cow_id_list
      • 最后通过dict(zip(ids, yields)) 创建字典。 zip 用于按索引同时迭代 2 个列表。
      • 应用dict 将根据结果对创建一个字典。

      为了进一步改进您的逻辑,我建议您考虑添加一些控件;例如,确保 ids 实际上由 3 位数字组成。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-20
        • 1970-01-01
        • 2021-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        相关资源
        最近更新 更多