首页 > 解决方案 > 如何制作一个替换特定索引的函数

问题描述

我不认为我已经完全掌握了函数的概念,所以它抑制了我进一步发展自己的能力。我有这个我无法弄清楚的挑战,就在这里。我不清楚如何设置一个函数来做我想要它做的事情,因为括号中的参数让我失望。如果您能告诉我方法而不是修复代码,我会更喜欢它。非常感谢您花时间阅读和/或回复。

Function Challenge: create replacement function¶

    Create a function, str_replace, that takes 2 arguments: int_list and index
        int_list is a list of single digit integers
        index is the index that will be checked - such as with int_list[index]
    Function replicates purpose of task "replace items in a list" above and replaces an integer with a string "small" or "large"
    return int_list

int_list = [3, 6, 9]
index = int_list[0]
def str_replace(int_list, index=""):
    if int_list[0] < 5:
        index = 'small'
    else:
        index = 'large'
    print(index)
    return str_replace(int_list)

标签: pythonpython-3.x

解决方案


这解决了我的问题。

int_list = [1,2,3,4,5]  # list created def str_replace(int_list, index): # index is a static position you will type in.
    if int_list[index] < 5:
        int_list[index] = "small"
    else:
        int_list[index] = "large"
    print "Your index is: ", index 
    print int_list[:]



str_replace(int_list,1)

推荐阅读