【问题标题】:Random Macro-nutrient selection (Python)随机宏量营养素选择(Python)
【发布时间】:2020-10-22 01:54:44
【问题描述】:

我目前正在尝试构建一个代码,从表中随机选择食物(具有宏观营养分解)。

我想知道的是我如何告诉Python“打印你随机选择的食物的索引 作为列表”?

【问题讨论】:

  • 一种方法是搜索列表中的项目(使用index 方法)。但我想简单地随机选择一个索引而不是一个项目要容易得多 - 然后你就可以免费获得索引,并且该项目很容易访问(使用 [] 运算符)
  • 最好重新设计帖子的标题。宏量营养素不是 Python 构造,您要解决的问题是编程问题,而不是生物化学。 :) 你能告诉我们到目前为止你尝试了什么吗?代码 sn-ps 会有所帮助。

标签: python list random


【解决方案1】:

假设我们的输入如下所示:

import numpy as np

macro_nutrients = [
    'carbohydrates',
    'fats',
    'dietary_fiber',
    'minerals',
    'proteins',
    'vitamins',
    'water'
]

您有多种选择:

  1. 如果您的宏量营养素存储在类似列表的结构中,您可以这样做:

    el = np.random.choice(macro_nutrients)
    idx = macro_nutrients.index(el)
    print(el, ";  Is the index correct?:", el == macro_nutrients[idx])
    
    # or you can just write:
    idx = np.random.randint(0, len(macro_nutrients) - 1)
    print(macro_nutrients[idx])
    

    对于[].index(),您可以查看this SO answer 的注意事项。

  2. 如果您有类似表格的结构(例如 numpy 二维数组):

    # we will simulate it by permuting the above list several times and adding the
    # permutation as a row in the new 2d array:
    mat = np.array([np.random.permutation(macro_nutrients.copy()),
                   np.random.permutation(macro_nutrients.copy()),
                   np.random.permutation(macro_nutrients.copy()),
                   np.random.permutation(macro_nutrients.copy())])
    
    # flatten() will convert your table back to 1d array
    np.random.choice(mat.flatten())
    
    # otherwise, you can use something like:
    row = np.random.randint(0, mat.shape[0] - 1)
    col = np.random.randint(0, mat.shape[1] - 1)
    print(mat[row, col])
    

【讨论】:

    猜你喜欢
    • 2020-05-26
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2011-01-01
    • 2014-04-23
    相关资源
    最近更新 更多