【问题标题】:Understanding the sample list within this function [duplicate]了解此函数中的示例列表 [重复]
【发布时间】:2018-03-16 15:20:56
【问题描述】:

我试图从 edx intro to python 课程中更好地理解这段代码的机制。我已经标记了我感到困惑的部分。

重新构建问题:

为什么不能设置成

my_min = sample_list[10]

my_min = sample_list[0,1]
############# 示例解决方案
def _find_min_sample_(sample_list):
    # Initially set the first element
    # of the list as the minimum
    my_min = sample_list[0]     # <---this is where i am confused.
    # Iterate through the list
    for item in sample_list:
        # Compare each item from the list
        # to the current minimum. If the item is smaller
        # than your current minimum then set that item
        # to be your current minimum instead
        if item < my_min:
            my_min = item
    # finally return the minimum value
    return my_min 

_find_min_sample_([-10,8,9,7])

【问题讨论】:

  • 可以my_min 设置为 sample_list[valid_index]sample_list[0:1] 或列表中的任何其他单个值,因为您检查了所有值
  • @Chris_Rands,但输入列表只有 4 个项目。似乎 OP 不明白它是一个整数索引器。
  • 您能否详细说明整数索引器是什么?我显然是 python 新手,对此并不熟悉。

标签: python


【解决方案1】:

如果您设置my_min = sample_list[10],如果您的列表中的元素少于 11 个,它将失败。

您(几乎)确定您的列表中至少有一个元素,因此您使用sample_list[0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多